【问题标题】:Java Generics :The method compareTo(capture#2-of ? extends E) in the type Comparable is not applicable for the arguments (Comparable)Java 泛型:Comparable 类型中的方法 compareTo(capture#2-of ? extends E) 不适用于参数 (Comparable)
【发布时间】: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() &amp;&amp; stack2.peek().compareTo(e) 应该会导致错误。

标签: java generics


【解决方案1】:

E 只需实现Comparable&lt;E&gt; :

public static <E extends Comparable<E>> void sort(IStack<E> stack) {
    IStack<E> stack2=new MyLinkedStack<>();

    while(!stack.isEmpty()){
        E e=stack.pop();
        while(stack2.isEmpty() && stack2.peek().compareTo(e)){
            //some code to be written
        }
    }
}

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2021-05-17
    • 2011-12-22
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    相关资源
    最近更新 更多