4

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.

Cory N.
  • 103
  • 1
  • 6

1 Answers1

6

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.

Mark Peters
  • 76,122
  • 14
  • 153
  • 186
  • 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. – Cory N. May 27 '14 at 01:01
  • 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? – John Meyer Feb 27 '21 at 17:06