我有以下课程签名:
public class SkipListSet<T extends Comparable<T>> implements SortedSet<T>
和SkipListSet类之外的另一个类:
class Node<T extends Comparable<T>>
第二个充当包装类,其中包含以下内容:
T data;
List<Node<T>> tower;
Node<T> nextNode = null;
Node<T> prevNode = null;
当我尝试在Node类中实现compareTo()方法时:
public int compareTo(T somePayLoad) {
if (this.data < somePayLoad)
return -1;
else if (this.data > somePayLoad)
return 1;
else
return 0;
}
我收到以下错误:
SkipListSet.java:171: error: bad operand types for binary operator '<'
if (this.data < somePayLoad)
^
first type: T
second type: T
where T is a type-variable:
T extends Comparable<T> declared in class SkipListSet.Node
为什么不能在compareTo方法中比较两种类型的T数据?
答案 0 :(得分:2)
不能在对象上使用'<'或'>'。我认为您需要的是:
public int compareTo(T somePayLoad) {
return this.data.compareTo(somePayLoad.data);
}
(添加空检查)。
答案 1 :(得分:0)
您不需要编写compareTo方法。 T类应实现Comparable接口。
TestSkipListSet<NodeData> list = new TestSkipListSet<NodeData>();
TestSkipListSet<NodeData2> list2 = new TestSkipListSet<NodeData2>();
class NodeData implements Comparable<NodeData> {
int value;
@Override
public int compareTo(@NonNull NodeData o) {
return this.value - o.value;
}
}
class NodeData2 implements Comparable<NodeData2> {
TestUser value;
@Override
public int compareTo(@NonNull NodeData2 o) {
return this.value.age-o.value.age;
}
}
class TestUser{
int age;
}
public class TestSkipListSet<T extends Comparable<T>> implements SortedSet<T>{
...
}