Skip to content
Advertisement

Finding Java Enum types from code values?

We use code values in our database, and Enums in Java. When querying the database, we need to take a code value and get an Enum instance.

Is it overkill to have a HashMap to avoid iteration? What would you do? Is there an easier way?

public enum SomeEnum
{
    TYPE_A(2000), TYPE_B(2001);

    private int codeValue;

    private static HashMap<Integer, SomeEnum> codeValueMap = new HashMap<Integer, SomeEnum>(2);

    static
    {
        for (SomeEnum  type : SomeEnum.values())
        {
            codeValueMap.put(type.codeValue, type);
        }
    }

    //constructor and getCodeValue left out      

    public static SomeEnum getInstanceFromCodeValue(int codeValue)
    {
        return codeValueMap.get(codeValue);
    }
}

Advertisement

Answer

That’s exactly the approach I’d take to solve that particular problem. I see nothing wrong with it from a design point of view, it’s intuitive, efficient and (as far as I can see) does exactly what it should.

The only other sensible approach I can think of would be to have the map in a separate class and then call that class to update the map from SomeEnum‘s constructor. Depending on the use case, this separation could be beneficial – but unless it would have a hard benefit I would take your approach and encapsulate everything within the enum itself.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement