3

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?

Magnilex
  • 11,584
  • 9
  • 62
  • 84
user3663882
  • 6,957
  • 10
  • 51
  • 92

3 Answers3

4

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.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
  • So, yeah it's clear that the array's order will be consistent with the enum's one. But what about `Arrays.asList()` method? Is it specified that the method doesn't chahnge the order? – user3663882 Jul 02 '15 at 08:19
  • So, I didn't find the order of the list returned by Arrays.asList is reliable. [docs](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)) I guess, if we need reliable order we'll have to construct a list on our own... – user3663882 Jul 02 '15 at 08:22
  • The order of `asList()` is predictable, I have clarified this in my answer. – Magnilex Jul 02 '15 at 08:38
2

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?

Community
  • 1
  • 1
David Soroko
  • 8,521
  • 2
  • 39
  • 51
0

If you want to maintain Order of Elements use LinkedList: -

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

AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23