我想实现一个通用 TreeNode 和一个通用树。我在 stackoverflow 和其他地方看过几个例子,但不能完全理解。
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 类?
基本上,我想了解在创建泛型类而不是泛型类型时要遵循的原则。
谢谢。