【发布时间】:2016-02-21 10:31:55
【问题描述】:
我正在编写通用代码来对堆栈进行排序,但在调用 comareTo 时收到警告:
public class StackUtility {
public static <E extends Comparable<? extends E>> void sort(IStack<E> stack) {
IStack<E> stack2 = new MyLinkedStack<>();
while (!stack.isEmpty()) {
Comparable<? extends E> e = stack.pop();
while (stack2.isEmpty() && stack2.peek().compareTo(e)>0) {
// some code to be written
}
}
}
}
注意:pop 和 peek 的返回类型是 E。
在调用 compareTo 时,我收到了来自 Eclipse 的警告:
类型中的方法 compareTo(capture#2-of ? extends E) 可比性不适用于 论据(可比)
在没有警告的情况下这样做的写入方式是什么。
【问题讨论】:
-
附带说明:
compareTo(...)确实返回int,因此stack2.isEmpty() && stack2.peek().compareTo(e)应该会导致错误。