我有这个简单的节点:
public class Node<T> implements Comparable<Node>{
T value;
Node<T> next;
public Node(T value){
this.value = value;
this.next = null;
}
public int compareTo(Node other){
return this.value.compareTo(other.value);
}
}
Eclipse 要求我转换“this.value”。用 int 强制转换是行不通的。应该怎么做呢?
最佳答案
您的 T 声明不会“扩展”Comparable,因此您无法使用它进行比较。
您可以将其更改为:
public class Node<T extends Comparable<T>> implements Comparable<Node<T>>{
T value;
Node<T> next;
public Node(T value){
this.value = value;
this.next = null;
}
public int compareTo(Node<T> other){
return this.value.compareTo(other.value);
}
}
这假设 T 实现了 Comparable。 否则,如果 T 不是真正的可比较对象,您可以只在节点级别进行比较。但你可能仍然应该像这样声明你的类
public class Node<T extends Something>
这样您就可以在进行比较时使用 Something
中的方法。
如果我回到开头:当你实例化你的节点时,你会做这样的事情:
Node<MyType> node = new Node<MyType>();
MyType 成为您的 T。MyType 是可比的吗?如果是这样,您可以如上所示声明您的类。否则,您将无法执行 T.compareTo(又名 MyType.compareTo),因此您需要使用 MyType 中的其他字段来执行比较。
我希望这足够清楚..
关于java - 如何将compareTo与节点一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38669735/