为什么 compareTo 在 Java 中的 Enum final 上? [英] Why is compareTo on an Enum final in Java?

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

问题描述

Java 中的枚举实现了 Comparable 接口.重写 ComparablecompareTo 方法会很好,但这里它被标记为 final.EnumcompareTo 上的默认自然顺序是列出的顺序.

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.

有谁知道为什么 Java 枚举有这个限制?

Does anyone know why a Java enums have this restriction?

推荐答案

为了一致性,我猜...当你看到 enum 类型时,你知道事实它的自然顺序是声明常量的顺序.

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.

要解决此问题,您可以轻松创建自己的 Comparator 并在需要不同排序时使用它:

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

更多信息:

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

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