我有一個簡單的數組列表設置,但我似乎無法添加對象。無法添加到ArrayList「錯位的結構」
import java.util.ArrayList;
public class Inventory {
ArrayList inventory = new ArrayList();
String item1 = "Sword";
String item2 = "Potion";
String item3 = "Shield";
inventory.add(item1);
inventory.add(item2);
inventory.add(item3);
}
有兩個誤區,一是在庫存和增加,以及一個在括號中的變量名之間的點,是
Syntax error on token(s), misplaced construct(s)
和
Syntax error on token "item1", VariableDeclaratorId expected after this token
誰能解釋爲什麼發生這種情況?
這應該寫在一個方法。 – Maroun
此外,使用raw arraylist可能不是最好的主意,而是使用ArrayList –
Zavior
您也可以編寫'Arrays.asList(「Sword」,「Potion」,「Shield」);' – LaurentG