Comparable and (MyClass)null

Say I have

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

The docs for Comparable say that "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."

it says that " e.compareTo(null) should throw a NullPointerException ".

Should it throw NullPointerException also when doing e.compareTo((MyClass)null) ?


Yes, it should throw a NullPointerException.

null is null at runtime, no matter what type you give it at compile-time.

Your code has no way to figure out if you called e.compareTo((MyClass)null) or e.compareTo(null) . It's the same.


What difference does it make if you write e.compareTo(null) or e.compareTo((MyClass)null) ?

Both code are one and the same, as 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/76224.html

上一篇: assertEquals抛出一个NullPointerException,但equals方法不会

下一篇: Comparable和(MyClass)null