为什么Java Enum需要在compareTo方法中检查类和declaringClass [英] Why Java Enum need to check class and declaringClass in compareTo method

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

问题描述

枚举中的类型参数 E 定义为< E扩展枚举< E> 。那么为什么在枚举实现源代码代码,我们还需要检查 getClass() getDeclaringClass() compareTo 方法中?我不认为编译器可以在 compareTo 中设置不同的枚举类型对象时传递。

解决方案

它涵盖了比较原始类型和通过不安全/未检查的转换和转换获得的值(例如 Comparable Object a ):

  static enum Fruit {Apple,Orange,Banana}; 
static enum动物{猫,狗,马};

public static final void main(String [] args)throws异常{
枚举f = Fruit.Apple;
枚举a = Animal.Cat;
f.compareTo(a);
}

有, compareTo 将在明确的 getDeclaringClass 比较中使用 ClassCastException 失败,因为它将通过第一个显式转换(枚举其他=(枚举)o )没有问题。



至于比较 getClass ,它被标记为该源中的优化。这是一个优化的原因是如果价值类别相同,那么他们是绝对从同一个枚举,所以没有必要调用稍微更昂贵的 getDeclaringClass 。由于绝大多数枚举都可能是简单的枚举(没有价值类的机构),因此针对这种情况进行了优化。


Type parameter E in Enum is defined as <E extends Enum<E>>. So why in Enum implementation source code, we still need to check getClass() and getDeclaringClass() in compareTo method? I don't think compiler can pass when I set a different enum type object in compareTo.

解决方案

It covers the case of comparing raw types and values obtained via unsafe / unchecked casts and conversions (such as Comparable, or Object a):

static enum Fruit { Apple, Orange, Banana };
static enum Animal { Cat, Dog, Horse };

public static final void main (String[] args) throws Exception {   
    Enum f = Fruit.Apple;
    Enum a = Animal.Cat;
    f.compareTo(a);
}

There, compareTo would fail with a ClassCastException at the explicit getDeclaringClass comparison, as it would pass the first explicit cast (Enum other = (Enum)o) with no issue.

As for comparing getClass, it's tagged as an "optimization" in that source. The reason this is an optimization is that if the value classes are the same, then they're definitely from the same enum, and so there's no need to call the slightly more expensive getDeclaringClass. Since the vast majority of enums are likely simple enums (no value class bodies), it's optimized for that case.

这篇关于为什么Java Enum需要在compareTo方法中检查类和declaringClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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