请帮助一个困惑的新手。我目前正在练习使用 add、remove、contains 和 toString 等方法实现二叉搜索树。我可以实现该类以使用整数值,但我无法弄清楚如何在二叉搜索树上使用泛型。我想灵活一点,也想为我的二叉搜索树或者我的 Card 类使用字符串。
public class MyTree<E> {
private class Node implements Comparable<E> {
private E data;
private Node left;
private Node right;
public Node(E data) {
this.data = data;
}
public int compareTo(E other) {
return this.data.compareTo(other); //ERROR HERE
//(Cannot Find Symbol at method CompareTo(E))
}
}
private Node root;
private int size;
public int getSize() {
return size;
}
public void add(E value) {
this.root = add(value, root);
}
private Node add(E value, Node currentRoot) {
if (currentRoot == null) {
Node temp = new Node(value);
size++;
return temp;
} else {
if (currentRoot.compareTo(value) > 0)
currentRoot.left = add(value, currentRoot.right);
else if (currentRoot.compareTo(value) < 0)
currentRoot.right = add(value, currentRoot.right);
return currentRoot;
}
}
我得到一个错误。
return this.data.compareTo(other);
^
symbol: method compareTo(E)
location: variable data of type E
where E is a type-variable:
E extends object declared in class MyTree
当我的 Node 类中有 compareTo(E other) 时,为什么找不到 compareTo。我在我的 Node 类中实现了 Comparable 接口,但我不知道为什么。我也尝试过使用 Comparable 工具,但这也不起作用。