On IntelliJ IDEA. Unable to add String to ArrayList<String>. Error: "Cannot resolve symbol 'add' "
On IntelliJ IDEA. Unable to add String to ArrayList<String>. Error: "Cannot resolve symbol 'add' "
static List<String> commands = new ArrayList<>(asList("Hello", "Goodbye"));
commands.add("Hi!");
编译器错误:
错误:(37, 17) java:<identifier>
预期
错误:(37, 18) java: 非法开始类型
这些位置在 .add() 的左括号前后;
像这样:
class MyClass {
static List<String> commands = new ArrayList<>(asList("Hello", "Goodbye"));
commands.add("Hi!");
}
是非法的。您不能在 class 定义中调用方法。
要使其工作,请使用静态块:
class MyClass {
static List<String> commands = new ArrayList<>(asList("Hello", "Goodbye"));
static {
commands.add("Hi!");
}
}
static List<String> commands = new ArrayList<>(asList("Hello", "Goodbye"));
commands.add("Hi!");
编译器错误:
错误:(37, 17) java:<identifier>
预期
错误:(37, 18) java: 非法开始类型
这些位置在 .add() 的左括号前后;
像这样:
class MyClass {
static List<String> commands = new ArrayList<>(asList("Hello", "Goodbye"));
commands.add("Hi!");
}
是非法的。您不能在 class 定义中调用方法。
要使其工作,请使用静态块:
class MyClass {
static List<String> commands = new ArrayList<>(asList("Hello", "Goodbye"));
static {
commands.add("Hi!");
}
}