Alexandros Katechis
Alexandros Katechis

Reputation: 1022

Java's Comparable Interface: Handling null arguments to compareTo()

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?

Upvotes: 2

Views: 2865

Answers (3)

Alanmars
Alanmars

Reputation: 1277

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.

Upvotes: 1

Jeffrey
Jeffrey

Reputation: 44808

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.

Upvotes: 4

Gelin Luo
Gelin Luo

Reputation: 14373

I prefer to throw NullPointerException rather than ClassCastException.

This convention is also followed by JDK implementations.

Upvotes: 3

Related Questions