Give different variable value to last enum value

I want the last enum to have a different value in one of the variables:

private enum thing {
    thing0(0),
    thing1(1),
    thing2(2);

    int index;
    String s;

    private thing(int index) {
        this.index = index;
        s = index == values().length - 1 ? "b" : "a";
    }
}

This doesn’t work; you can’t call values() in the constructor. Is there another way?

>Solution :

In general, don’t rely on the declaration order of the enum values. Item 35 in Effective Java 3rd Ed, "Use instance fields instead of ordinals", explains why. (Note that whilst you are using an instance field for s, its value depends on the ordinal.)

If you want a particular value to have a particular property, pass it in as a constructor parameter.

private enum thing {
    thing0(0),
    thing1(1),
    thing2(2, "b");

    int index;
    String s;

    private thing(int index) {
        this(index, "a");
    }

    private thing(int index, String s) {
        this.index = index;
        this.s = s;
    }
}

If you really do want it to be checking for the last value in the enum, an alternative way to do this is with a getter. Initialize a static final field in the enum to be the last value:

// Invokes `values()` twice, but meh, it's only executed once.
private static final thing LAST = values()[values().length-1];

Then check in a getter:

String s() {
  return this == LAST ? "b" : "a";
}

Leave a Reply