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

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

    Your "adding" statements are just "in the air": not inside one method or constructor.

    Wrap in inside one like for instance:

    public class Inventory {
    
       private List inventory = new ArrayList();  //prefer interface here ;)
    
       public Inventory(){   //statements wrap into this constructor
          inventory.add("Sword");
          inventory.add("Potion");
          inventory.add("Shield");
       }
    }
    

提交回复
热议问题