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?
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.
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.
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.
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.