Java's enums have been around for a while, and it's no surprise that you might run into trouble as new features have been released. This article attempts to cover a few odd cases of enum in action so you don't repeat mistakes of the past.

Enum Abstract Method

An enum type can have abstract methods just like a class. Each enum constant needs to implement the abstract method. An example is as follows:

EnumMap: Enum as a Key

EnumMapis a specialized implementation of Map provided for cases where an enum is used as the key. According to the Javadocs, the storage is compact and efficient. It is used similarly to the way regular Maps are used, with some change in construction; the enum class must be passed into the constructor.

Enum Name Map

The implementation of the values() method creates an array every time it is invoked. To avoid invoking this method too many times, you can create a name map and use it for lookup. (Yes, that might possibly count as “premature optimization” but hopefully you are resorting to this approach only when invoking values() multiple times.)

Sometimes you may want to store or transmit the ordinal as a part of storing the state. Should you use the ordinal in such cases? For instance:

System.out.println("4 => " + days[4]); // prints 4 => THURSDAY

The answer is no, it is not a good idea to store or use the ordinal. It is a much better idea to store and transmit the name. Since the values() method returns the array in the order of declaration, using the ordinal might return wrong values if the enum definition is modified to add or remove entries.

Store and use the name. If the enum entry is removed later, valueOf() will throw an exception. Which is much better than using wrong values and not knowing about it.

Summary

We have now learned some basics about enums in Java. Enums in java are more powerful than in most other languages. Abstract methods can be declared for the enum and specialized implementation can be defined for each enum constant. Looking up enum constants in a case-insensitive operation is another area arising frequently.