为什么在Java中的枚举最后的compareTo? [英] Why is compareTo on an Enum final in Java?

查看:196
本文介绍了为什么在Java中的枚举最后的compareTo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的枚举实现了Comparable接口。可以重写Comparable的compareTo方法,但在这里它被标记为final。枚举的compareTo的默认自然顺序是列出的顺序。有没有人知道为什么Java Enum有这个限制?

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 Enum has this restriction?

推荐答案

为了保持一致性,我猜...当你看到一个枚举类型,你知道一个事实,它的自然排序是声明常量的顺序。

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.

要解决这个问题,您可以轻松创建自己的比较器< MyEnum> ,并在需要不同的顺序时使用:

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
    }
}

您可以使用 Comparator 直接:

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);    

更多信息:

  • The Java Tutorial on Enum Types
  • Sun's Guide to Enums
  • Class Enum API

这篇关于为什么在Java中的枚举最后的compareTo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆