【发布时间】:2015-12-07 15:11:21
【问题描述】:
我正在实现一个简单的 Tree 数据结构。 我的目标是在 Tree 类中创建一个 Node 类型的对象。 在这种情况下,我不明白如何管理泛型。
这是我的细树结构:
public class RBT<K extends Comparable<K>, V> {
Node<K,V> a = null;
Node<Integer,String> b = null;
public RBT() {
this.a = new Node<K,V>(new Integer(1), new String("node1")); // ERROR
this.b = new Node<Integer, String>(new Integer(1), new String("node1"));
this.a = this.b; // ERROR!
}
public void newNode(K key, K value) {
Node<K,V> test = new Node<K,V>(key, value); // ERROR
}
public static void main(String[] args) {
RBT<Integer,String> rbt = new RBT<Integer,String>();
rbt.newNode(new Integer(2), new String("node2")); // ERROR!
}
}
这是我的节点表示:
public class Node<K,V> {
private Node<K,V> father;
private Node<K,V> left;
private Node<K,V> right;
private K key;
private V value;
Node(K key, V value) {
this.father = this.left = this.right = null;
this.key = key;
this.value = value;
}
}
提前感谢您的帮助。
【问题讨论】:
-
最后我找到了另一个有趣的解决方案。我已经在 RBT 类
private class Node { }中将 Node 类声明为私有(注意我省略了)。这样可以更轻松地管理泛型。