[英]Java Generics in a Binary Tree, incompatible types error
我正在嘗試使用泛型在 Java 中實現二叉樹,我搜索並發現了這個問題: 在 Java 中使用泛型 Comparable<T> 數據實現二叉樹? ,但我無法解決我的疑慮。 所以我有兩個班級,
BST_Tree<T>
和
Node<T extends Comparable<T>>
我希望我的實現可以:
獲取每種類型的 Object 並將其放入 Node 中的字段key
中
將每個節點與key
段進行比較
這是代碼:
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;
}
}
我的 Node 類假設擴展Comparable
以比較鍵。
這是我的樹:
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;
}
}
我的樹嘗試在節點 z 中設置鍵,但它失敗了。 這是錯誤:
不兼容的類型:T 不能轉換為 java.lang.Comparable
先感謝您!
您的
public class BST_Tree<T>
應該
public class BST_Tree<T extends Comparable<T>>
BST_Tree
和Node
類中的每個Node
變量都應該是Node<T>
。
這將確保您只能使用實現Comparable
元素類型實例化BST_Tree
類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.