5

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.

1
  • RED(new int[]{255,0,0}) should work fine, although @Mark Peters's solution is ideal. Commented Aug 3, 2016 at 9:49

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I only tried the new int[] for a single line, which is why it didn't work. When I replaced all three lines, it did however work. Good point about the varags.
Varargs won't work for more than one array at the end of the arg list; in that case, array constructor new T[] is helpful. Therefore, can we say that the syntax is allowed as a literal argument to the enum element?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.