问题:
我在树类型数据结构上实现递归add()方法,使用表示树节点的泛型类实现。
情况详情:
我有一个泛型类集(下面是一个地图),用于实现对象(基本上是N级树)的地图映射。
public interface NodeInterface<KeyType, ValueType> {
public void add(List<KeyType>, ValueType);
public ValueType getSubTree(KeyType); // Get subtree map
}
// Generic map class.
// Leaf level nodes are maps too, just not maps containing other maps
public abstract class NodeMap <KeyType, ValueType> implements NodeInterface<> {
protected Map<KeyType, ValueType> map; // actual map
...
}
// Leaf level objects - map NOT containing other maps
public class LeafNode extends NodeMap <String, MyDataType> {
public void add(List<KeyType>, ValueType) {} // implementation for leaf add
...
}
// Tree nodes (non-leaf)
public class ParentNodeMap <ValueType extends NodeMap <?,?>>
extends NodeMap <String, ValueType> {
// This class is needed because there are methods that must be
// implemented on a map that can't be implemented on leaf level nodes.
...
}
// Actual tree node classes (needed as syntactic sugar, to avoid end users
// having to deal with HashMap<String, Hashmap<String, HashMap<String, ...MyDataType>>>>>
public class Level2Node extends ParentNodeMap <LeafNode> {
}
public class Level1Node extends ParentNodeMap <Level2Node > {
}
需要做什么:
我试图实现一个方法,该方法将叶级对象递归插入到这个地图的地图中(在界面中描述)。
,例如,期望的行为是:
tree = new Level1Node();
List<String> keys = Arrays.asList("key1", "key2"); // I think I need 3 here? irrelevant.
MyDataType data = new MyDataType();
tree.add(keys, data);
问题:
我似乎无法在ParentNode的add()
方法中实现子树地图的创建和插入
这是我在ParentNodeMap类中尝试的:
public void add(List<KeyType> keys, ValueType value);
KeyType key = getFirstKey(keys);
createMapIfNull(); // creates "map" as new HashMap<KeyType, ValueType>()
ValueType subTree = getSubTree(key); // Gets me child subtree from map
// PROBLEM! that subtree is now "null" since we just created an new Map
// which has no key "hey"
// Now here's where we should create a new subtree and add it:
if (subTree == null) {
subTree = new ValueType<>(); // THIS IS WHAT FAILS!!!!
map.put(key, subTree);
subTree.add(keys.removeFirstKey(), value); // recursively add to subtree
}
现在,我特别坚持的是:如何创建一个subTree对象(NodeMap类型);其类型是通用的ValueType extends NodeMap <?,?>
,我所知道的是什么?
调用new ValueType()
给出&#34;无法实例化类型ValueType&#34;错误。