wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets 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: http://aspose.com/file-tools
subject: Enums in a map
Similar Threads
shifting to the next enum in the list
Start java enum ordinal at 1 instead of 0
Locales and Ordinal values
How to sort a Map with Enums
cast int to an enum