1
我想实现一个通用TreeNode和通用树。我在stackoverflow和其他地方看过几个例子,但不能完全理解。通用树和通用节点Java
public interface Node<K, V>
{
K getId();
V getData();
K getParentId();
void addChild(Node<K, V> child);
List<Node<K, V>> getChildren();
}
public class Tree<K, V>
{
private Node<K, V> root;
public void loadData(Map<K, V> data)
{
// by figuring out the root node from map, populate tree
// root node is the one with parentId as null
// and the logic follows. Simple level order insertion
}
}
虽然上面的代码服务器我的目的,我想了解是否有更好的方法来实现这一目标。
喜欢声明Tree作为
public class Tree<T extends Node<?, ?>
{
private T root;
public void loadData(Map<K, V> data)
{
// by figuring out the root node from map, populate tree
// root node is the one with parentId as null
// and the logic follows. Simple level order insertion
}
}
在上述情况下,我的数据负载的方法应该驻留在何处?一些Util类?
基本上,我想了解创建通用类型的类时要遵循的原则,而类型又是通用的。
谢谢。
如何将你的第二个代码工作,你的类型是'T'只有通用 - 那么'K'和'V'从哪里来? –
我想你所拥有的是不错。除非你想允许“树的任何东西”,并有像'接口树'和定义类'NodeTree 实现树>' –
Bohemian
http://stackoverflow.com/questions/10265836/declare-a-binary- tree-which-take-a-generic-type-of-node-which-contain-a-generi?rq = 1这正是我所期待的。不过,由于我发布这一天只是一天,我想等待几天,看看是否有更好的答案。 – Gopal