List order

Consider the following enumeration:

public enum Type{
     INTEGER,
     DOUBLE,
     BOOLEAN
}

      

Now I have the following line:

List<Type> types = Arrays.asList(Type.values());

      

Does the list contain items in the same order as the enumeration? Is this order reliable?

+3


source to share


3 answers


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 return an array with constants as they are declared.

As for the method Arrays.asList()

, you can also rely on its order:



Returns a fixed-size list supported by the specified array. (Changes to the returned "write through" list to the array.)

Consider the example below, which is a very common way to initialize List

:

List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

      

The order of the list will be the same as in the array.

+4


source


The JLS mentions that values()

"Returns an array containing the constants of this enumeration type, in the order in which they are declared." ( http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9 ). So, you can assume that the order will be the same until your enum type changes



For some details see How are values ​​() implemented for Java 6 enums?

+2


source


If you want to keep the order of the elements use LinkedList

: -

List<Type> types = new LinkedList<Type>(Arrays.asList(Type.values()));

0


source







All Articles