I'm recently returning to Java after 10 years and I'm pretty rusty. I'm trying to run some basic sorted list code I had. This code used to compile and run but now I'm getting the following warning:
.\LinkedList.java:30: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type Comparable
return _data.compareTo( ((Node)n)._data );
^
where T is a type-variable:
T extends Object declared in interface Comparable
This is the code throwing the warning:
static protected class Node implements Comparable
{
public Node _next;
public Comparable _data;
protected Node(Comparable data, Node next)
{
_next = next;
_data = data;
}
public int compareTo(Object n)
{
return _data.compareTo( ((Node)n)._data );
}
public String toString()
{
return _data.toString();
}
} // end Node class
My understanding is I can no longer use compareTo() on a raw type, but I'm not sure how to go about fixing it. Any help welcome. Also new to stack overflow so forgive me if I've done this wrong or missed where this has already been answered.
There are two (three) different types of ordering:
Generally:
Comparableis a Generic Class, so you should actually useComparable<T>(T being a class-type), in your example use it reflexively asComparable<Node>so the compiler knows you have a comparableNodethat you want to compare to another (comparable) Node.Ordering Type 1:
Comparable<T>is used when you have an natural ordering on an element, and the elements incidates its own ordering behaviour.Your Code redone:
1: Nodes that can be compare to Ts, which usually is problematic:
2: Node that can be compared to other nodes, and the T it is containing must be Comparable also:
This is the default implementation you would use in your case.
Ordering Type 2: Using a task-specific ordering:
This is in contrast to the situation above. Here, it's not the element that dictates ordering, but the task at hand:
The code for the Class does not necessarily need to (but still can) specify an ordering implementation. But then the ordering is done on specific contents with a specific ordering
Comparator:... and of course Type 3, where you mix both, i.e. have an
implements Comparable<>somewhere in the mix and using that