33

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

I have an enum something like below :-

enum Direction {

    EAST,
    WEST,
    NORTH,
    SOUTH
}

If i say values() on the Direction enum, then will the order of the value remain same all the time. I mean will the order of values will be in the below foramt always:

EAST,WEST,NORTH,SOUTH

or can the order change at any point of time.

Community
  • 1
  • 1
M.J.
  • 16,266
  • 28
  • 75
  • 97

4 Answers4

51

Each Enum type has a static values method that returns an array containing all of the values of the enum type in the order they are declared.

This method is commonly used in combination with the for-each loop to iterate over the values of an enumerated type.

Java 7 Spec documentation link : http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.2

Ajay George
  • 11,759
  • 1
  • 40
  • 48
7

The behaviour of that method is defined in the Java Language Specification #8.9.2:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum   
* type, in the order they're declared.  This method may be  
* used to iterate over the constants as follows:  
*  
*    for(E c : E.values())  
*        System.out.println(c);  
*  
* @return an array containing the constants of this enum   
* type, in the order they're declared  
*/  
public static E[] values();
assylias
  • 321,522
  • 82
  • 660
  • 783
3

Enums are used to restrict the values of the variables to one of the only declared values in the enumerated list.

These values are public static final, ie (Constant objects of that specific Enum Type), and its Order is very Important for mapping the variables to these Objects.

values() is a static method of Enum, which always returns the values in same order.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
1

As the previous 2 answers say, the order is the order of declaration. However, it is not good practice to rely on this order (or on the enum's ordinal). If someone reorders the declaration or adds a new element in the middle of the declaration, the behavior of the code may change unexpectedly. If there is a fixed order, I'd implement Comparable.

Heiko Schmitz
  • 300
  • 1
  • 4