Java – cannot add to ArrayList “misplaced construct (s)”
I have a simple ArrayList setting, but I can't seem to add objects
import java.util.ArrayList; public class Inventory { ArrayList inventory = new ArrayList(); String item1 = "Sword"; String item2 = "Potion"; String item3 = "Shield"; inventory.add(item1); inventory.add(item2); inventory.add(item3); }
There are two errors, a point between inventory and addition, and a variable name between parentheses
Syntax error on token(s),misplaced construct(s)
and
Syntax error on token "item1",VariableDeclaratorId expected after this token
Can anyone explain why?
Solution
The reason your code doesn't work is that you try to write code in the class body Executable statements should be written with static initializers, methods, or constructors (as I did in the following example)
Try this:
public class Inventory { private List inventory = new ArrayList(); public Inventory() { String item1 = "Sword"; String item2 = "Potion"; String item3 = "Shield"; inventory.add(item1); inventory.add(item2); inventory.add(item3); } }
I defined the class member inventory in the class body and initialized it in place (= new arraylist();) There are no compiler errors because declarations are allowed in class bodies The rest of the code I put in the constructor initializes the inventory with values I could put it in a method, but I chose the constructor because it usually initializes class members