Is it good practice to use ordinal of enum?

TLDR: No, you should not!

If you refer to the javadoc for ordinal method in Enum.java:

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.

Firstly – read the manual (javadoc in this case).

Secondly – don’t write brittle code. The enum values may change in future and your second code example is much more clear and maintainable.

You definitely don’t want to create problems for the future if a new enum value is (say) inserted between PARENT and GRANDPARENT.

Leave a Comment