这是我在这里的第一篇文章,但我需要帮助来弄清楚为什么我的子类不允许我覆盖父方法。
我的任务是创建一个具有某些功能的通用二叉搜索树。下一个任务是创建一个通用的 AVL 树,我决定从我的自定义二叉搜索树扩展它以重用代码,并简单地添加使其功能所需的旋转。
但是,当尝试覆盖该方法时,我不断收到名称冲突错误。如果我在我的 AVLTree 类中去掉 Comparable 接口扩展并使我的插入方法通用,我会收到一个参数不匹配错误,说 T 无法转换为 Comparable。
这就是我坚持的地方,如果有人可以提供任何类型的输入,将不胜感激。
public class BinaryTree <T extends Comparable<T>>{
Node Root;
public BinaryTree(){
this.Root = null;
}
public boolean isEmpty(){
return this.Root == null;
}
public void insert(T data){
this.insert(data, this.Root);
}
protected void insert(T data, Node<T> n){
if(this.Root == null){
this.Root = new Node(data);
}
if(data.equals(n.getData())){
n.occurances++;
}
else if(data.compareTo(n.data) < 0){
if(n.left != null)
insert(data, n.left);
else
n.left = new Node(data);
}
else if(data.compareTo(n.data) > 0){
if(n.right != null)
insert(data, n.right);
else
n.right = new Node(data);
}
}
第一次尝试:
public class AVLTree <T extends Comparable<T>> extends BinaryTree{
private static final int ALLOWED_IMBALANCE = 1;
public void insert(T data){
this.insert(data, this.Root);
}
第二次尝试:
public class AVLTree extends BinaryTree{
private static final int ALLOWED_IMBALANCE = 1;
public <T>void insert(T data){
this.insert(data, this.Root);
}