Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Java Enum types from code values?

Tags:

java

enums

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);
    }
}
like image 827
Andy Avatar asked Feb 22 '11 02:02

Andy


2 Answers

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.

like image 156
Michael Berry Avatar answered Sep 19 '22 10:09

Michael Berry


Thanks, I guess my main concern is memory usage, and if it is worth it.

Unless that enum has thousands of values, memory usage will be trivial. (And if it does have thousands of values, then using iteration to do the lookup would be a major performance killer.)

This is a sensible use of memory, IMO.

Perhaps I am over thinking this.

Perhaps you are.

like image 37
Stephen C Avatar answered Sep 17 '22 10:09

Stephen C