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

后端 未结 5 1801
孤城傲影
孤城傲影 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:17

    A more general answer would be that the class body is about declarations, not statements. There is special provision for statements occurring in class body, but they have to be marked explicitly as either class initializers or instance initializers. As the assignments are statements and statements are allowed only inside blocks of code(methods, constructors, static initializers, etc.). So you can do as below,

    public class Inventory {
    
    ArrayList inventory = new ArrayList();
    
    String item1 = null;
    String item2 = null;
    String item3 = null;
    
    //initializer block
    {
    item1="Sword";
    item2="Potion";
    item3="Shield";
    
    inventory.add(item1);
    inventory.add(item2);
    inventory.add(item3);
    }
    

提交回复
热议问题