Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Enums in a map

 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd like to be able to go from an ordinal number to the enum. I thought I had a glorious solutioun by having a static map, and having part of the enum constructer be to put yourself into the map with your ordinal as your key. The compiler blows thi up with "Cannot refer to static enum field Code.OTC within an initializer."

1. Why can't it?
2. How do I get around it?

Thanks,
Nick
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Nick]: I'd like to be able to go from an ordinal number to the enum.


[Nick]: 1. Why can't it?

Consider that the values of an enum type are essentially static variables that need to be initialized, using a constructor. Since (for readability, I assume) the enum values are required to be listed first, that means the constructor must run for each of those values, before any other static fields have been initialized. If the compiler did not prevent you from accessing static fields from the constructor, any such field would be null or zero anyway.

There are other ways they could have set up the rules, but my guess is they'd probably be more confusing or error-prone.

[Nick]: 2. How do I get around it?

Aside from the code I gave above to get a value from the ordinal, if in the future you need to initialize a static Map or other structure based on enum values, you can use a static initializer, e.g.:

However for anything related to ordinal or to field name, there are already implicit methods & structures that can be used for lookup, so this isn't necessary.
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Awesome.
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic