2012-06-25 46 views
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类?

基本上,我想了解创建通用类型的类时要遵循的原则,而类型又是通用的。

谢谢。

+0

如何将你的第二个代码工作,你的类型是'T'只有通用 - 那么'K'和'V'从哪里来? –

+1

我想你所拥有的是不错。除非你想允许“树的任何东西”,并有像'接口树'和定义类'NodeTree 实现树>' – Bohemian

+0

http://stackoverflow.com/questions/10265836/declare-a-binary- tree-which-take-a-generic-type-of-node-which-contain-a-generi?rq = 1这正是我所期待的。不过,由于我发布这一天只是一天,我想等待几天,看看是否有更好的答案。 – Gopal

回答

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) 
     { 
      // ... 
     } 
    } 

我不知道如果我得到你的意思,它不是从问题是什么是很清楚您的需求,因此,如果这是没有意义的,或只是不正是你所需要的,请让我知道之前downvote我(:?

问候