【发布时间】:2026-01-21 12:00:02
【问题描述】:
在集合中经常使用Comparable 接口,例如。在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;
...
}
说,我们创建整数队列并添加一些东西:
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(1);
如果我正确理解了通配符的概念,使用<? super T> 而不是<T> 的唯一效果是编译器扩展了compareTo 的可能参数类型
public interface Comparable<T> {
public int compareTo(T o);
}
到Integer 的任何超类。
但我想知道为什么以及如何在这里使用它。
任何示例
Comparable<T> key = (Comparable<T>) x;
还不够吗?或者将“超级”通配符与 Comparable 一起使用是一种指导方针?
【问题讨论】:
标签: java generics collections wildcard