I can write an enum
with properties besides the name and ordinal. A very generic example would be:
public enum ExampleEnum {
EXAMPLE0(Example.example0),
EXAMPLE1(Example.example1),
EXAMPLE2(Example.example2);
public final Example identifier;
private ExampleEnum(final Example identifier) {
this.identifier = identifier;
}
}
In this case where Example
is an arbitrary user-defined class with several pre-existing instances available as static
fields. Every ExampleEnum
instance has an associated, unique Example
instance, but not the other way around. But what if I wanted to get an ExampleEnum
(or null
if there is no associated value) from a given Example
instance? There are a few ways to do this:
public ExampleEnum get(Example identifier) {
return
identifier == Example.example0 ? EXAMPLE0 :
identifier == Example.example1 ? EXAMPLE1 :
identifier == Example.example2 ? EXAMPLE2 :
null
;
}
This is terrible. A very long chained conditional statement that needs to be modified by hand if a new ExampleEnum
instance is added at a later point. Also a slow linear search.
A better option is a hash table:
private Map<Example, ExampleEnum> map = new HashMap<Example, ExampleEnum>();
private ExampleEnum(final Example identifier) {
map.put(this.identifier = identifier, this);
}
public ExampleEnum get(final Example identifier) {
return map.get(identifier);
}
The issue with this is a rule in Java that you cannot access static
fields in an enum
from the constructor. To get around this, it just so happened that in my use case I had a static enum
inside another class. I just placed the private static
map
field in the class instead of the enum
.
However, this seems a hack to fix a problem that is not applicable to all cases, for example, if the enum
is not inside another class. Alternatively I could create a single class whose sole purpose is to store these map
objects but that is not modular, as the enum
and the related map(s) are no longer self-contained.
How could I handle reverse enum
queries as described, in a way that respects modularity (does not place the map
in unrelated classes just to circumvent the enum
restriction) and that is graceful (not just a terrible if else
or ? :
chain)?