Java "unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable"

3mpty picture 3mpty · Jan 28, 2011 · Viewed 28.7k times · Source

I'm trying to implement a sorted list as a simple exercise in Java. To make it generic I have an add(Comparable obj) so I can use it with any class that implements the Comparable interface.

But, when I use obj.compareTo(...) anywhere in the code I get "unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable" from the compiler (with -Xlint:unchecked option). The code works just fine but I can't figure out how to get rid of that annoying message.

Any hints?

Answer

axtavt picture axtavt · Jan 28, 2011

In essence, this warning says that Comparable object can't be compared to arbitrary objects. Comparable<T> is a generic interface, where type parameter T specifies the type of the object this object can be compared to.

So, in order to use Comparable<T> correctly, you need to make your sorted list generic, to express a constraint that your list stores objects that can be compared to each other, something like this:

public class SortedList<T extends Comparable<? super T>> {
    public void add(T obj) { ... }
    ...
}