无法添加到 ArrayList 中的“错位构造"; [英] Can't add to an ArrayList "misplaced construct(s)"

查看:23
本文介绍了无法添加到 ArrayList 中的“错位构造";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个简单的数组列表,但似乎无法向其中添加对象.

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 ArrayList();

String item1 = "Sword";
String item2 = "Potion";
String item3 = "Shield";

inventory.add(item1);
inventory.add(item2);
inventory.add(item3);
}

有两个错误,一个在inventory和add之间的点上,一个在括号之间的变量名上,是

There are two errors, one at the dot between inventory and add, and one at the variable names between the brackets, being

Syntax error on token(s), misplaced construct(s)

Syntax error on token "item1", VariableDeclaratorId expected after this token

谁能解释为什么会这样?

Can anyone explain why this is happening?

推荐答案

你的代码不起作用的原因是你试图在类体中编写代码.可执行语句应该写在静态初始化器、方法或构造器中(就像我在下面的例子中所做的那样).

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).

试试这个:

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);
    }
}

我在类主体中定义了类成员 inventory 并就地初始化(= new ArrayList();).没有编译器错误,因为类主体中允许声明.我放入构造函数的其余代码将用值初始化 inventory.我可以把它放在一个方法中,但我选择了构造函数,因为它通常的作用是初始化类成员.

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.

这篇关于无法添加到 ArrayList 中的“错位构造";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆