java - Order in which values of an enum are constructed -
are there guarantees on order in values of enum constructed?
for example, given
enum myenum { a, b, c; static list<myenum> list = new arraylist<>(); myenum(){ list.add(this); } }
would true list.get(0)==myenum.a
, list.get(1)==myenum.b
etc., or not necessarily?
yes.
quoting jls section 8.9.3 (emphasis mine):
for each enum constant c declared in body of declaration of e, e has implicitly declared public static final field of type e has same name c. field has variable initializer consisting of c, , annotated same annotations c.
these fields implicitly declared in same order corresponding enum constants, before static fields explicitly declared in body of declaration of e.
an enum constant said created when corresponding implicitly declared field initialized.
side note, code not compile since accessing static list inside initializer. can write instead:
static list<myenum> list = new arraylist<>(); static { (myenum myenum : myenum.values()) { list.add(myenum); } // list.get(0) == myenum.a, list.get(1) == myenum.b }
Comments
Post a Comment