In Java, you sometimes encounter places where you need an enum with more than one name (or key). Here is the pattern that I use:
import java.util.HashMap; import java.util.Map; enum X { // "A" is the name of the enum, "a" is the second name/key. A("a"), B("b"); private final static Map<String,X> MAP = new HashMap<String,X>(); static { for( X elem: X.values() ) { if( null != MAP.put( elem.getValue(), elem ) ) { throw new IllegalArgumentException( "Duplicate value " + elem.getValue() ); } } } private final String value; private X(String value) { this.value = value; } public String getValue() { return value; } // You may want to throw an error here if the map doesn't contain the key public static X byValue( String value ) { return MAP.get( value ); } }
Things to note:
- There are additional parameters in () after the enum name.
- You need a custom constructor which accepts the additional parameters. Like other Java classes, you can have as many constructors as you need.
- I’m filling the static map from a static block inside of the enum declaration. Looks odd but works. Java will first create all instances and then invoke the static code in my custom enum.
- You can look up enum values by using the static method byValue(). The name is not very good (it’s easy to get confused with enum‘s valueOf()). When the field is called code, I use byCode(). So in real life, it will be less confusing.