【发布时间】:2012-10-23 08:20:59
【问题描述】:
我想编写一个通用的 Pair 类,它有两个成员:键和值。该类的唯一要求是键和值都应实现 Comparable 接口,否则 Pair 类将不接受它们作为类型参数。
首先我这样编码:
public class Pair<T1 extends Comparable, T2 extends Comparable>
但是 JDK 1.6 编译器会对此产生警告:
Comparable is a raw type. References to generic type Comparable<T> should be parameterized
然后我尝试添加类型参数,代码现在看起来像这样:
public class Pair<T1 extends Comparable<? extends Object>,
T2 extends Comparable<? extends Object>>
现在一切顺利,直到我尝试为 Pair 生成一个比较器。(以下代码在 Pair 类中)
public final Comparator<Pair<T1, T2>> KEY_COMPARATOR = new Comparator<Pair<T1, T2>>() {
public int compare(Pair<T1, T2> first, Pair<T1, T2> second) {
*first.getKey().compareTo(second.getKey());*
return 0;
}
};
代码first.getKey().compareTo(second.getKey()); 会产生错误提示:
The method compareTo(capture#1-of ? extends Object) in the type Comparable<capture#1-of ? extends Object> is not applicable for the arguments (T1)
有人知道这个错误信息是什么意思吗?
欢迎提供有关此主题的任何提示。
更新:
完整代码如下:
public class Pair<T1 extends Comparable<? extends Object>, T2 extends Comparable<? extends Object>> {
private T1 key;
private T2 value;
public static int ascending = 1;
public final Comparator<Pair<T1, T2>> KEY_COMPARATOR = new Comparator<Pair<T1, T2>>() {
public int compare(Pair<T1, T2> first, Pair<T1, T2> second) {
int cmp = first.getKey().compareTo((T1)(second.getKey()));
if (cmp > 0) return ascending;
return -ascending;
}
};
}
@MarvinLabs 你能解释一下为什么编译器不能确保将对象与相同类型的其他对象进行比较。上述代码中second.getKey()返回T1类型,与first.getKey()属于同一类型
【问题讨论】:
-
如果您仍有问题,请查看我的编辑。如果不是,请接受对您有帮助的回答。
标签: java generics comparator comparable