Passing Array Constant to enum Constructor

arrays, enums, java

Solution

You can't use the literal form here, because that syntax is only allowed in the declaration of the variable. But you could use the varargs syntactic sugar, which is actually shorter.

enum Color {
    RED(255,0,0),
    GREEN(0,255,0),
    BLUE(0,0,255);

    int[] rgb;

    Color(int... rgb) {
        this.rgb = rgb;
    }
}

And contrary to what you have said, `RED(new int[]{255, 0, 0})` works just fine.

Problem

Java enum lets you pass arguments to the constructor, but I can't seem to pass an array. For instance, the following code compiles with out error: ``` 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; } } ``` But if this same data is passed in as an array constant, the code will not compile: ``` enum Color { RED({255,0,0}), GREEN({0,255,0}), BLUE({0,0,255}); int[] rgb; Color(int[] rgb) { this.rgb = rgb; } } ``` I have also tried variations of creating a new int[] array, like: ``` ... RED(new int[]{255,0,0}), ... ``` with no luck. I think the problem lies in passing an array constant. I'm not sure if it is a simple syntax that needs to be corrected or if there is an underlying problem with passing this type of data. Thanks in advance.

Original source

Related problems