I have a simple arraylist set up, but I can\'t seem to add objects to it.
import java.util.ArrayList;
public class Inventory {
ArrayList inventory = new A
In Java, you cannot have executable statements, such as invocations of the add method, outside a definition of a method or a constructor. Declarations are OK, but executable statements are not.
You can add these items to a named constructor, but you can also use an anonymous initialization block, like this:
public class Inventory {
ArrayList inventory = new ArrayList();
{ // An anonymous initialization block
String item1 = "Sword";
String item2 = "Potion";
String item3 = "Shield";
inventory.add(item1);
inventory.add(item2);
inventory.add(item3);
}
}
If you use a block like that, it would be shared among all named constructors of the class, or it would become part of the implicitly generated constructor for the Inventory.