File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Enums in a map" Watch "Enums in a map" New topic
Author

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?

Thanks,
Nick


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

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
Awesome.
Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Enums in a map