enum.values() - is an order of returned enums deterministic

JavaEnumsSpecifications

Java Problem Overview


I have a enum SOME_ENUM:

public enum SOME_ENUM {
  EN_ONE,
  EN_TWO,
  EN_THREE;
}

Will SOME_ENUM.values() always return the enums in the order of enum declarations: EN_ONE, EN_TWO, EN_THREE? Is it a rule or it is not guaranteed to be not changed in the next JDK releases?

Java Solutions


Solution 1 - Java

The Java language specification uses this explicit language:

> @return an array containing the constants of this enum type, in the order they're declared [Source]

So, yes, they will be returned in declaration order. It's worth noting that the order might change over time if someone changes the class so be very careful about how you use this.

Solution 2 - Java

Yes, it is a guaranteed to return them in that order.

However you should avoid relying on that, and on the ordinal() value, since it can change after inserting new items, for example.

Solution 3 - Java

It is determined by the order your values are declared in. However, there is no guarantee that you (or someone else) won't reorder / insert / remove values in the future. So you shouldn't rely on the order.

Effective Java 2nd. Edition dedicates its Item 31 to a closely related topic: Use instance fields instead of ordinals:

> Never derive a value associated with an enum from its ordinal; store it in an instance field instead.

Solution 4 - Java

The other answers are good, but don't comment on this:

> "Is it a rule or it is not guaranteed to be not changed in the next > Jdk releases?"

I don't believe that guarantees on future JDKs exist, so you shouldn't even worry about them. There would be no way to enforce them, future JDK leads might just decide to reneg on such guarantees. It's like the Westminster system of parliament: "No Parliament can bind a future parliament."

That said, the history of the JDK reveals excellent consistency. They don't make a lot of breaking changes, so you can be pretty confident that current specified (not just observed) behaviour will be preserved.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkarabView Question on Stackoverflow
Solution 1 - JavaGaryFView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow
Solution 3 - JavaPéter TörökView Answer on Stackoverflow
Solution 4 - JavaFletchView Answer on Stackoverflow