2016-07-04 67 views
1

我有這段代碼需要類型Comparable的泛型,我的類實現了Comparable接口。 我在類中的compareTo()方法收到錯誤,指出Comparable不能轉換爲T#1。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',而不是可比? 另外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

Edge類有一個類型參數,但您使用的是raw typeEdge沒有類型參數。添加類型參數:

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; 
} 
+0

謝謝。我做了建議的更改,但我仍然收到關於在一個實例上使用weight和另一個像這樣的weight()方法的錯誤 - > return(this.weight).compareTo(e.weight());任何想法爲什麼我會收到錯誤 - (Comparable不能轉換爲T)? –

+0

@DeeptiSabnani因爲你的方法'weight()'返回'Comparable'而不是'T',正如我在上面的回答中所提到的。 – Jesper

相關問題