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?

JavaScript

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