Why does Java enum need to check class and declaringclass in the CompareTo method

The type parameter E in enum is defined as < e extends enum < E > > So why do we need to check getClass () and getdeclarangclass () in the CompareTo method in the enum implementation source code? When I set different enumeration type objects in CompareTo, I don't think the compiler can pass

Solution

It covers comparing primitive types with 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 will fail due to ClassCastException in explicit getdeclaratingclass comparison because it will pass the first explicit conversion (enum other = (enum) o) without problem

As for comparing getClass, it is marked as "optimized" in the source This is an optimization because if the value classes are the same, they must come from the same enumeration, so there is no need to call the slightly expensive getdeclarangclass Because most enumerations may be simple enumerations (no value class body), it is optimized for this situation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>