Why is compareTo on an Enum final in Java?

后端 未结 5 813
感动是毒
感动是毒 2020-12-07 23:36

An enum in Java implements the Comparable interface. It would have been nice to override Comparable\'s compareTo method, but here it\

5条回答
  •  没有蜡笔的小新
    2020-12-08 00:28

    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 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
    {
        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 set = new TreeSet(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

提交回复
热议问题