2

Writing some classes for a Framework extension, and I have the following code:

public class TimeImpl implements Time, Comparable<TimeImpl>, Serializable
{
...
    public int compareTo(TimeImpl other)
    {
        if (other == null)
            throw new ClassCastException("null");
        return Long.valueOf(toSeconds()).compareTo(other.toSeconds());
    }
}

Pretty straightforward implementation, if you ask me. My question is: as far as I can tell, the javadocs for the Comparable interface say nothing regarding null arguments. Should I bother checking for it? Should I change the type of exception thrown, should I return some other value in that case? How are other people out there handling this?

  • Duplicate of [How to simplify a null-safe compareTo() implementation?](http://stackoverflow.com/questions/481813/how-to-simplify-a-null-safe-compareto-implementation) – ziesemer Jan 20 '12 at 02:00
  • 1
    possible duplicate of [Comparable and Comparator contract with regards to null](http://stackoverflow.com/questions/2858628/comparable-and-comparator-contract-with-regards-to-null) – Don Roby Jan 20 '12 at 02:00

3 Answers3

4

Actually, the Comparable interface does say something about handling null arguments.

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.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
3

I prefer to throw NullPointerException rather than ClassCastException.

This convention is also followed by JDK implementations.

Gelin Luo
  • 14,035
  • 27
  • 86
  • 139
1

The code below is the compareTo method of Integer from java:

 public int compareTo(Integer anotherInteger) 
 {
    int thisVal = this.value;
    int anotherVal = anotherInteger.value;
    return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
 }

why not implement your compareTo method in the way Integer does.

Alanmars
  • 1,267
  • 1
  • 11
  • 21
  • I've basically gone with something like this. Not sure why I didn't realize that invoking a method on the null pointer would throw the exception I needed, without have to explicitly check for null. – Alexandros Katechis Jan 20 '12 at 16:57