Comparable 和 (MyClass)null

Comparable and (MyClass)null

说我有

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

Comparable 的文档说 "The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false."

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

它是否也应该在执行 e.compareTo((MyClass)null) 时抛出 NullPointerException?

e.compareTo(null)e.compareTo((MyClass)null)有什么区别?

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

是的,它应该抛出 NullPointerException。

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

您的代码无法判断您是调用了 e.compareTo((MyClass)null) 还是 e.compareTo(null)。一样的。