Comparable和(MyClass)null

说我有

public class MyClass 
     implements Comparable<MyClass>
{
    public int compareTo(MyClass mc)
    {
        //<implementation ommited>...
    }
}

Comparable的文档说:“当且仅当e1.compareTo(e2)== 0与e1.equals(e2)具有相同的布尔值时,每个e1和e2。 请注意,null不是任何类的实例,即使e.equals(null)返回false ,e.compareTo(null)也应抛出NullPointerException

它说“ e.compareTo(null)应该抛出一个NullPointerException ”。

它应该抛出NullPointerException也做e.compareTo((MyClass)null)


是的,它应该抛出一个NullPointerException。

null在运行时是null的,不管你在编译时给它什么类型。

您的代码无法确定您是否调用了e.compareTo((MyClass)null)e.compareTo(null) 。 一样的。


如果您编写e.compareTo(null)e.compareTo((MyClass)null)什么不同?

两个代码都是一样的,因为null is null. Even if you cast it to any type, it will be null only null is null. Even if you cast it to any type, it will be null only

链接地址: http://www.djcxy.com/p/76223.html

上一篇: Comparable and (MyClass)null

下一篇: Overriding Proper Java equals method