请帮助一个困惑的新手。我目前正在练习使用诸如add,remove,contains和toString之类的方法来实现二进制搜索树。我可以实现该类以使用整数值,但无法弄清楚如何在二进制搜索树上使用泛型。我想灵活一点,也可以在我的Binary Search Tree或Card类中使用Strings。
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工具,但这也行不通。
问题是您已将E
参数作为参数传递给Comparable
它,但未定义。通常,实现的类Comparable
将自身作为参数传递给Comparable
(作为通用参数)。Comparable
应该用于比较相同类型的实例。但是,如果您看一下实现,就不会比较该类的两个实例,而只会value
在下面的add
方法行中将类的一个实例与另一个实例的字段进行比较:
if (currentRoot.compareTo(value) > 0)
您可以看到currentRoot
的类型为Node
,值的类型为E
。这是一个错误的实现,因为如果您要具有类型安全性,则不应比较不同类型的值(或者如果要比较它们,则它们绝不应该彼此相等,因为它们具有不同的类型),所以为什么不这样做您只是将两者values
相互比较?
另一方面E
是泛型类型,它不仅用于Node
类,E
也用于add
您的MyTree
类的方法中。因此,E
应该是class的泛型参数,MyTree
并且应该让MyTree
class的用户决定E
他想使用MyTree
class的确切类型是什么。另一个约束是E
应该实现的,Comparable
因为我们要相互比较类型的实例E
。
最后,您的课程将更改为这一课:
public class MyClassTree<E extends Comparable<E>> {
private class Node {
private E data;
private Node left;
private Node right;
public Node(E data) {
this.data = data;
}
}
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.data.compareTo(value) > 0)
currentRoot.left = add(value, currentRoot.right);
else if (currentRoot.data.compareTo(value) < 0)
currentRoot.right = add(value, currentRoot.right);
return currentRoot;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句