【发布时间】: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