Search code examples
javanullpointerexceptionnullcomparecomparable

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)?


Solution

  • 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.