0

Are there any guarantees on the order in which values of an enum will be constructed?

For example, given

enum MyEnum {
    A,
    B,
    C;

    static List<MyEnum> list = new ArrayList<>();
    MyEnum(){
        list.add(this);
    }
}

would it be true that list.get(0)==MyEnum.A, list.get(1)==MyEnum.B etc., or not necessarily?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Museful
  • 6,711
  • 5
  • 42
  • 68

2 Answers2

4

Yes.

Quoting the JLS section 8.9.3 (emphasis mine):

For each enum constant c declared in the body of the declaration of E, E has an implicitly declared public static final field of type E that has the same name as c. The field has a variable initializer consisting of c, and is annotated by the same annotations as c.

These fields are implicitly declared in the same order as the corresponding enum constants, before any static fields explicitly declared in the body of the declaration of E.

An enum constant is said to be created when the corresponding implicitly declared field is initialized.

Side note, your code does not compile since you are accessing a static list inside an initializer. You can write instead:

static List<MyEnum> list = new ArrayList<>();

static {
    for (MyEnum myEnum : MyEnum.values()) {
        list.add(myEnum);
    }
    // list.get(0) == MyEnum.A, list.get(1) == MyEnum.B
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
1

You can't access to static member from enum constructor so your code would not compile.

Check this answer

The constructor is called before the static fields have all been initialized, because the static fields (including those representing the enum values) are initialized in textual order, and the enum values always come before the other fields.

But you can move logic to static block;

static {
    for (MyEnum myEnum : MyEnum.values()) {
        list.add(myEnum);
    }
}
Community
  • 1
  • 1
Fatih Donmez
  • 4,319
  • 3
  • 33
  • 45
  • 1
    @tennenrishin, because all the enum constant instances are initialized during the static initialization of the enum class and before any user-specified static initialization code. – Tagir Valeev Oct 27 '15 at 15:17