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.
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.
CA1069: Enums should not have duplicate values (code analysis) - .
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.
The clone() method of Enum class throws CloneNotSupportedException. This method ensures that enums cannot be cloned, which helps to maintain their "singleton" property.
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With