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?
One possible explanation is that
compareTo
should be consistent withequals
.And
equals
for enums should be consistent with identity equality (==
).If
compareTo
where to be non-final it would be possible to override it with a behaviour which was not consistent withequals
, which would be very counter-intuitive.If you want to change the natural order of your enum’s elements, change their order in the source code.
Enumeration values are precisely ordered logically according to the order they are declared. This is part of the Java language specification. Therefore it follows that enumeration values can only be compared if they are members of the same Enum. The specification wants to further guarantee that the comparable order as returned by compareTo() is the same as the order in which the values were declared. This is the very definition of an enumeration.
Providing a default implementation of compareTo that uses the source-code ordering is fine; making it final was a misstep on Sun's part. The ordinal already accounts for declaration order. I agree that in most situations a developer can just logically order their elements, but sometimes one wants the source code organized in a way that makes readability and maintenance to be paramount. For example:
The above ordering looks good in source code, but is not how the author believes the compareTo should work. The desired compareTo behavior is to have ordering be by number of bytes. The source-code ordering that would make that happen degrades the organization of the code.
As a client of an enumeration i could not care less how the author organized their source code. I do want their comparison algorithm to make some kind of sense, though. Sun has unnecessarily put source code writers in a bind.
For consistency I guess... when you see an
enum
type, 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
Comparator
directly:or use it in collections or arrays:
Further information: