KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ashkelon > util > TreeNode


1 package org.ashkelon.util;
2
3 import java.util.Collection JavaDoc;
4 import java.util.Iterator JavaDoc;
5 import java.util.Map JavaDoc;
6 import java.util.TreeMap JavaDoc;
7
8 /**
9  * @author Eitan Suez
10  */

11 public class TreeNode
12 {
13    private TreeNode parent;
14    private Map JavaDoc children;
15    private Object JavaDoc value;
16    
17    public TreeNode()
18    {
19       parent = null;
20       children = new TreeMap JavaDoc();
21    }
22    
23    public TreeNode(Object JavaDoc value)
24    {
25       this();
26       setValue(value);
27    }
28    
29    public void setValue(Object JavaDoc value)
30    {
31       this.value = value;
32    }
33    public Object JavaDoc getValue()
34    {
35       return value;
36    }
37    
38    public TreeNode getParent()
39    {
40       return parent;
41    }
42    public void setParent(TreeNode parent)
43    {
44       this.parent = parent;
45    }
46    
47    public TreeNode getChild(String JavaDoc key)
48    {
49       return (TreeNode) children.get(key);
50    }
51    
52    public void addChild(String JavaDoc key, TreeNode child)
53    {
54       child.setParent(this);
55       children.put(key, child);
56    }
57    
58    public TreeNode getOnlyChild()
59    {
60       Iterator JavaDoc itr = children.values().iterator();
61       if (itr.hasNext())
62         return (TreeNode) children.values().iterator().next();
63       else
64         return null;
65    }
66    
67    public Map JavaDoc getChildren()
68    {
69       return children;
70    }
71    public void setChildren(Map JavaDoc children)
72    {
73       this.children = new TreeMap JavaDoc(children);
74    }
75    
76    public boolean isEmpty()
77    {
78       return (getChildren().values().size() == 0);
79    }
80    
81    
82    public static String JavaDoc printTree(TreeNode node, int level)
83    {
84       Object JavaDoc value = node.getValue();
85       if (value==null) return "";
86       
87       String JavaDoc caption = value.toString();
88       String JavaDoc indent = StringUtils.join(" ","",level);
89       String JavaDoc output = indent+caption+" ("+level+")\n";
90       
91       Map JavaDoc children = (Map JavaDoc) node.getChildren();
92       Collection JavaDoc values = children.values();
93       Iterator JavaDoc itr = values.iterator();
94       TreeNode childNode;
95       while (itr.hasNext())
96       {
97          childNode = (TreeNode) itr.next();
98          output += printTree(childNode, level + 1);
99       }
100       
101       return output;
102    }
103 }
104
Popular Tags