这行不通:
public enum TestEnum {
FOO({"foobar","foobaz"}); //This fails
private final String[] indicators;
TestEnum(String[] indicators){
this.indicators = indicators;
}
private String[] getIndicators(){
return this.indicators;
}
上面的代码编译失败。下面编译成功
public enum TestEnum {
FOO(new String[3]); //This is okay. Why?
private final String[] indicators;
TestEnum(String[] indicators){
this.indicators = indicators;
}
private String[] getIndicators(){
return this.indicators;
}
我的目标是提供一个可以由多个字符串表示的枚举。我知道 EnumMap
, 但它在这里不起作用,因为我感兴趣的映射来自 <String,enum>
.我也知道我可以使用普通的 Map
.我想我主要是好奇为什么 1 号不适合我。
最佳答案
表达式 {"foobar","foobaz"}
是一个数组初始化器,只有在直接声明数组时才有效。
尝试在 new String[]
之前添加:
FOO(new String[] {"foobar","foobaz"});
An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.
也就是说,你需要一个 array creation expression, section 15.10 .
关于java - 作为枚举成员的数组编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16347094/