More on Enums

Something that bothers me about Java Enums, is that they don’t represent ints out of the box.  Like no easy way to use them to represent particular indexes in an array, with the auto-incrementing thing happening, as per C/C++.

If you look a little deeper, there is the YOUR_ENUM.ordinal() method which will give you an int based on the position in your code that the ENUM_USED appears in the enum class, but the javadoc for ordinal makes you wary about using it

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as java.util.EnumSet and java.util.EnumMap.

Returns:
the ordinal of this enumeration constant

"Most programmers have no use for this method"…. This method emulates the old C way of doing enums and not specifying a default.  Surely many programmers would be at home with such a thing?

…. is there a better way to represent static constants of indexes that don’t use an enum?

Well, there are some articles on this question, and what exactly the java enum implementation can and can’t do.

Making the Most of Java 5.0: Enum Tricks

This article contains some really clever things you can do with Java enums, like having a static block in the enum to initialise a static Map or even cooler, using Enums to implement Template methods.

Leave a Reply