An enum in Java implements the Comparable interface. It would have been nice to override Comparable‘s compareTo method, but here it’s marked as final. The default natural order on Enum‘s compareTo is the listed order.
Does anyone know why a Java enums have this restriction?
For consistency I guess… when you see an
enumtype, you know for a fact that its natural ordering is the order in which the constants are declared.To workaround this, you can easily create your own
Comparator<MyEnum>and use it whenever you need a different ordering:You can use the
Comparatordirectly:or use it in collections or arrays:
Further information: