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

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

    The reason why your code does not work is that you tried to write code in the class body. Executable statements should be written in static initializers, methods or constructors (as I did in the example below).

    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();). No compiler error there because declarations are allowed in class body. The rest of the code I put into the constructor that will initialize inventory with values. I could have put it in a method, but I chose the constructor because its usual role is to initialize class members.

提交回复
热议问题