Can't add to an ArrayList “misplaced construct(s)”

后端 未结 5 1803
孤城傲影
孤城傲影 2020-12-11 23:02

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         


        
5条回答
  •  情书的邮戳
    2020-12-11 23:21

    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.

提交回复
热议问题