First, you probably don't even need a numeric order value -- that's
what Comparable
is for, and Enum<E>
implements Comparable<E>
.
If you do need a numeric order value for some reason, yes, you should
use ordinal()
. That's what it's for.
Standard practice for Java Enums
is to sort by declaration order,
which is why Enum<E>
implements Comparable<E>
and why
Enum.compareTo()
is final
.
If you add your own non-standard comparison code that doesn't use
Comparable
and doesn't depend on the declaration order, you're just
going to confuse anyone else who tries to use your code, including
your own future self. No one is going to expect that code to exist;
they're going to expect Enum
to be Enum
.
If the custom order doesn't match the declaration order, anyone
looking at the declaration is going to be confused. If it does
(happen to, at this moment) match the declaration order, anyone
looking at it is going to come to expect that, and they're going to
get a nasty shock when at some future date it doesn't. (If you write
code (or tests) to ensure that the custom order matches the
declaration order, you're just reinforcing how unnecessary it is.)
If you add your own order value, you're creating maintenance headaches
for yourself:
- you need to make sure your
hierarchy
values are unique
- if you add a value in the middle, you need to renumber all
subsequent values
If you're worried someone could change the order accidentally in the
future, write a unit test that checks the order.
In sum, in the immortal words of Item 47:
know and use the libraries.
P.S. Also, don't use Integer
when you mean int
.