views:

53

answers:

3

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?

+2  A: 

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.

Bozho
+1 for the sage advice. On the topic of ordinal(), Effective Java suggests adding a member field to the enum type.
ide
+3  A: 

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.

Péter Török
+4  A: 

The Java language specification uses this explicit language:

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

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.

GaryF
I am careful ;).
Skarab