[英]Java Generics in a Binary Tree, incompatible types error
I'm trying to implement a Binary Tree in java with Generics, i searched and i find this question: Implementing Binary Tree in Java with Generic Comparable<T> data?我正在尝试使用泛型在 Java 中实现二叉树,我搜索并发现了这个问题: 在 Java 中使用泛型 Comparable<T> 数据实现二叉树? , but i couldn't resolve my doubts.
,但我无法解决我的疑虑。 So i have two classes,
所以我有两个班级,
BST_Tree<T>
and和
Node<T extends Comparable<T>>
I want that my implementation can:我希望我的实现可以:
Take every type of Object and put it inside the field key
in Node获取每种类型的 Object 并将其放入 Node 中的字段
key
中
Compare every node with the key
field将每个节点与
key
段进行比较
This is the code:这是代码:
public class Node < T extends Comparable < T >> {
private T key;
private Node left;
private Node right;
private Node p;
public void setKey(T key) {
this.key = key;
}
public T getKey() {
return key;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
public void setP(Node p) {
this.p = p;
}
public boolean getBolCompMin(T key) {
return this.key.compareTo(key) < 0;
}
}
My Node class is suppose to extend Comparable
in order to compare the key.我的 Node 类假设扩展
Comparable
以比较键。
This is my tree:这是我的树:
public class BST_Tree < T > {
private ArrayList < Node > nodes;
private Node root;
public BST_Tree(Node root) {
this.root = root;
}
public void insertNode(T key) {
Node z = new Node();
z.setKey(key);
Node x = this.root;
Node y = new Node();
while (x != null) {
y = x;
if (z.getBolCompMin(x.getKey())) {
x = x.getLeft();
} else {
x = x.getRight();
}
}
z.setP(y);
if (z.getBolCompMin(y.getKey())) {
y.setLeft(z);
} else {
y.setRight(z);
}
}
public void InOderWalk(Node x) {
if (x != null) {
InOderWalk(x.getLeft());
System.out.println(x.getKey());
InOderWalk(x.getRight());
}
}
public Node getRoot() {
return root;
}
}
My tree tries to set the key in node z but it fails.我的树尝试在节点 z 中设置键,但它失败了。 This is the error:
这是错误:
incompatible types: T cannot be converted to java.lang.Comparable
不兼容的类型:T 不能转换为 java.lang.Comparable
Thank you in advance!先感谢您!
Your您的
public class BST_Tree<T>
should be应该
public class BST_Tree<T extends Comparable<T>>
And every Node
variable inside your BST_Tree
and Node
classes should be Node<T>
. BST_Tree
和Node
类中的每个Node
变量都应该是Node<T>
。
This would ensure that you can only instantiate your BST_Tree
class with element types that implement Comparable
.这将确保您只能使用实现
Comparable
元素类型实例化BST_Tree
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.