Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will the order for enum.values() always same [duplicate]

Tags:

java

enums

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.

like image 868
M.J. Avatar asked Aug 10 '12 09:08

M.J.


People also ask

Does order matter in enum?

the difference with enum is that the order of the members matters. To implement this feature the compiler team would have to add new features that would explicitly specify that behavior.

Can enums have duplicate values?

CA1069: Enums should not have duplicate values (code analysis) - .

What is the order of the variables in enum?

1. What is the order of variables in Enum? Explanation: The order of appearance of variables in Enum is their natural order (the natural order means the order in which they are declared inside Enum type). However, the compareTo() method is implemented to order the variable in ascending order.

What happens if we invoke clone () on an enum constant?

The clone() method of Enum class throws CloneNotSupportedException. This method ensures that enums cannot be cloned, which helps to maintain their "singleton" property.


2 Answers

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

like image 86
Ajay George Avatar answered Oct 23 '22 12:10

Ajay George


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();
like image 7
assylias Avatar answered Oct 23 '22 13:10

assylias