Java Coding Tip: Avoid using enum .ordinal()
When using enums in Java, you might be tempted to use the .ordinal() method, since it’s listed in the documentation as a way to get to the internal ordinal of the enumeration constant, in other words, the position index of the specific enum value in the declaration (See: https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#ordinal%28%29)
But, don’t do that. It’s not a good practice — plus, the Java documentation gives a warning: “Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap, to get the same result.”
Output:
Don’t use enum .ordinal() this way for indexing
Number of DWARF candidates: 3
Number of ELF candidates: 4
Number of HOBBIT candidates: 5
Number of HUMAN candidates: 2
Use the EnumMap directly with .forEach() for the same result
Number of DWARF candidates: 3
Number of ELF candidates: 4
Number of HOBBIT candidates: 5
Number of HUMAN candidates: 2
So, instead just use EnumMap directly so that you can keep yourself out of trouble. Using EnumMap directly, like the second way in the above Java code, is not using any internal values that may change in the future, is not tightly binding something that should be loosely coupled, and can be coded in one simple line of code instead of five lines of code. The last reason should be enough by itself.
Hinkmond





