可比较无法转换为T#1

时间:2016-07-04 13:48:43

标签: java generics comparable

我有这段代码,它采用了Comparable类型的Generic,我的类实现了Comparable Interface。 我在类中的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());
    }

}

1 个答案:

答案 0 :(得分: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;
}