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);
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With