Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading