This week's book giveaways are in the iOS and Features new in Java 8 forums.
We're giving away four copies each of Barcodes with iOS: Bringing together the digital and physical worlds and Core Java for the Impatient and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Enums in a map Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Barcodes with iOS this week in the iOS forum
or Core Java for the Impatient in the Java 8 forum!

JavaRanch » Java Forums » Java » Java in General
Bookmark "Enums in a map" Watch "Enums in a map" New topic

Enums in a map

Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
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?


I've heard it takes forever to grow a woman from the ground
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
[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.

"I'm not back." - Bill Harding, Twister
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
I agree. Here's the link:
subject: Enums in a map