Java 枚举允许您将参数传递给构造函数,但我似乎无法传递数组。例如,下面的代码编译没有错误:
enum Color {
RED(255,0,0),
GREEN(0,255,0),
BLUE(0,0,255);
int[] rgb;
Color(int r, int g, int b) {
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果同样的数据作为数组常量传入,代码将无法编译:
enum Color {
RED({255,0,0}),
GREEN({0,255,0}),
BLUE({0,0,255});
int[] rgb;
Color(int[] rgb) {
this.rgb = rgb;
}
}
Run Code Online (Sandbox Code Playgroud)
我还尝试了创建新 int[] 数组的变体,例如:
...
RED(new int[]{255,0,0}),
...
Run Code Online (Sandbox Code Playgroud)
没有运气。我认为问题在于传递数组常量。我不确定它是否是需要更正的简单语法,或者传递此类数据是否存在潜在问题。提前致谢。
您不能在此处使用文字形式,因为该语法仅允许在变量声明中使用。但是你可以使用 varargs 语法糖,它实际上更短。
enum Color {
RED(255,0,0),
GREEN(0,255,0),
BLUE(0,0,255);
int[] rgb;
Color(int... rgb) {
this.rgb = rgb;
}
}
Run Code Online (Sandbox Code Playgroud)
与您所说的相反,RED(new int[]{255, 0, 0})效果很好。