【问题标题】:Comparable cannot be converted to T#1Comparable 无法转换为 T#1
【发布时间】:2016-07-04 13:48:43
【问题描述】:

我有这段代码,它采用 Comparable 类型的 Generic,我的类实现了 Comparable 接口。 我在类中的 compareTo() 方法上收到一个错误,指出 Comparable 无法转换为 T#1。

完整的错误信息是->

Edge.java:40: error: method compareTo in interface Comparable<T#2> cannot be applied to given types;    
    return (this.weight).compareTo(e.weight());
                        ^
    required: 
        T#1 found: Comparable reason: argument mismatch; Comparable cannot be converted to T#1    where 
    T#1,T#2 are type-variables: 
        T#1 extends Comparable<T#1> declared in class Edge 
        T#2 extends Object declared in interface Comparable
1 error

(this.weight) 不应该返回类型 'T' 而不是 Comparable 吗? weight() 方法也返回 Comparable。

我完全不明白这一点。如果有人能澄清我为什么会收到此错误,那就太好了。 用 this.weight() 替换 this.weight 后,错误就消失了。

public class Edge<T extends Comparable<T>> implements Comparable<Edge>{
    private int vertex1;
    private int vertex2;
    private T weight;

    public Edge(int vertex1, int vertex2, T weight){
        this.vertex1 = vertex1;
        this.vertex2 = vertex2;
        this.weight = weight;
    }

    public int either(){
        return vertex1;
    }

    public int from(){
        return vertex1;
    }

    public int other(){
        return vertex2;
    }

    public int to(){
        return vertex2;
    }

    public Comparable weight(){
        return weight;
    }

    public String toString(){
        String s = "";
        s += vertex1 + " " + vertex2 + " " + weight;
        return s;
    }

    @Override
    public int compareTo(Edge e){
        return (this.weight).compareTo(e.weight());
    }

}

【问题讨论】:

    标签: java generics comparable


    【解决方案1】:

    您的类Edge 有一个类型参数,但您使用的raw type Edge 没有类型参数。添加类型参数:

    public class Edge<T extends Comparable<T>> implements Comparable<Edge<T>> {
        // ...
    
        @Override
        public int compareTo(Edge<T> e) {
            return this.weight.compareTo(e.weight);
        }
    }
    

    另外,为什么weight() 方法返回Comparable?它应该返回T

    public T weight() {
        return weight;
    }
    

    【讨论】:

    • 谢谢。我进行了建议的更改,但我仍然收到在一个实例上使用权重和在另一个实例上使用 weight() 方法的错误,例如 -> return (this.weight).compareTo(e.weight());知道为什么我会收到错误 - (Comparable 无法转换为 T)?
    • @DeeptiSabnani 因为你的方法weight() 返回Comparable 而不是T,正如我在上面的回答中提到的那样。
    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 2017-05-27
    • 1970-01-01
    • 2016-02-13
    • 2019-07-10
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多