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

Skarab picture Skarab · Sep 29, 2010 · Viewed 30.6k times · Source

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?

Answer

GaryF picture GaryF · Sep 29, 2010

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.