1

我想实现一个通用 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 类?

基本上,我想了解在创建泛型类而不是泛型类型时要遵循的原则。

谢谢。

4

1 回答 1

0

如果您需要孔树类型泛型,这是我能想到的唯一选择:

    public class Tree<K extends Object, V extends Object, T extends Node<K, V>>
    {
       private T root;
       public void loadData(Map<K, V> data) 
       {
             // ...
       } 
    }

我不确定我是否明白了你的意思,从这个问题中你的需求是什么并不清楚,所以如果这没有意义或者不完全是你所需要的,请在否决我之前让我知道(:

问候。

于 2012-11-07T17:59:58.570 回答