Reputation: 7357
Consider the following enum:
public enum Type{
INTEGER,
DOUBLE,
BOOLEAN
}
Now, I have the following line:
List<Type> types = Arrays.asList(Type.values());
Do the list contains the elements in the same order they put into the enum? Is this order reliable?
Upvotes: 3
Views: 181
Reputation: 11978
Yes. The Java Language Specification for Enums states:
/**
* 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();
It will returned an array with the constants as they are declared.
Regarding the Arrays.asList()
method, you can rely on its order as well:
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
Consider the below example, which is a very common way to initialize a List
:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
The order of the list will be the same as in the array.
Upvotes: 4
Reputation: 9086
The JLS mentions that values()
"Returns an array containing the constants of this enum type, in the order they're declared." (http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9). So yes, you can assume that the order will be the same as long as your enum type doesn't change
For some details see How is values() implemented for Java 6 enums?
Upvotes: 2
Reputation: 2820
If you want to maintain Order of Elements use LinkedList
: -
List<Type> types = new LinkedList<Type>(Arrays.asList(Type.values()));
Upvotes: 0