In collections casting to Comparable
interface is often used, eg. in PriorityQueue
:
private static <T> void siftUpComparable(int k, T x, Object[] es) {
Comparable<? super T> key = (Comparable<? super T>) x;
...
if (key.compareTo((T) e) >= 0)
break;
...
}
Say, we create queue of integers and add something:
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(1);
If I get the concept of wildcards right, the only effect of using <? super T>
instead of <T>
is that compiler extends the possible argument type of compareTo
public interface Comparable<T> {
public int compareTo(T o);
}
to any superclass of Integer
.
But I'm wondering why and how it can be used here.
Any example where
Comparable<T> key = (Comparable<T>) x;
is not enough? Or it's kind of guideline to use "super" wildcard with Comparable?