This article explains how Java enums work and different ways to lookup Enums based on their values. It also explains the performance of different approaches of java enum reverse lookup and performance of valueof method.
Enums were introduced as part of JDK5 version to enable programmers to create a set of constants with below characteristics-
- Enum types can’t be declared as abstract and final, it results in compilation error.
- Enum types can’t be explicitally instantiated. Nested Enum types are implicitally static.
- All enums defined in the code implicitally extends from abstract class Enum.java provided in JDK.
- Two Enum constants can be compared using == operator without the need to call equals method. Equals method in abstract class “Enum.java” is made final so that it can’t be overriden by the programmers.
How does Jdk ensures that programmer can’t instantiate Enum constant by all available means?
- Clone method in abstract class Enum is made final and throws CloneNotSupported Exception.
Snippet from Java’s Enum class-
- Initializing Enum constants using Reflection throws exception.
- Serialization mechanism ensures that duplicate enums are not initialized as part of deserialization. It gives the existing Enum present in memory.
On next page we are going to see in what scenarios reverse lookup is required for enums and how to do that.