Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is compareTo on an Enum final in Java?

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?

like image 886
neu242 Avatar asked Feb 06 '09 10:02

neu242


People also ask

How does compareTo work with enum?

The compareTo() method of Enum class compares this enum object with the defined object for order. Enum constants can only be compared to other enum constants of the same type. Returns: A negative integer, if this enum is less than the defined object.

Why is enum final?

Java does not allow you to create a class that extends an enum type. Therefore, enums themselves are always final, so using the final keyword is superfluous.

Does compareTo have to be overridden?

So essentially you need to override compareTo() because you need to sort elements in ArrayList or any other Collection.

Why do we override compareTo method?

In order to change the sorting of the objects according to the need of operation first, we have to implement a Comparable interface in the class and override the compareTo() method. Since we have to sort the array of objects, traditional array.


1 Answers

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:

enum MyEnum {     DOG("woof"),     CAT("meow");      String sound;         MyEnum(String s) { sound = s; } }  class MyEnumComparator implements Comparator<MyEnum> {     public int compare(MyEnum o1, MyEnum o2)     {         return -o1.compareTo(o2); // this flips the order         return o1.sound.length() - o2.sound.length(); // this compares length     } } 

You can use the Comparator directly:

MyEnumComparator c = new MyEnumComparator(); int order = c.compare(MyEnum.CAT, MyEnum.DOG); 

or use it in collections or arrays:

NavigableSet<MyEnum> set = new TreeSet<MyEnum>(c); MyEnum[] array = MyEnum.values(); Arrays.sort(array, c);     

Further information:

  • The Java Tutorial on Enum Types
  • Sun's Guide to Enums
  • Class Enum API
like image 86
Zach Scrivena Avatar answered Sep 22 '22 00:09

Zach Scrivena