Enums With More Than One Name

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:

  1. There are additional parameters in () after the enum name.
  2. You need a custom constructor which accepts the additional parameters. Like other Java classes, you can have as many constructors as you need.
  3. 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.
  4. 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.

One Response to Enums With More Than One Name

  1. […] Enums With More Than One Name (pdark.de) […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: