1 package org.ashkelon.util; 2 3 import java.util.Collection ; 4 import java.util.Iterator ; 5 import java.util.Map ; 6 import java.util.TreeMap ; 7 8 11 public class TreeNode 12 { 13 private TreeNode parent; 14 private Map children; 15 private Object value; 16 17 public TreeNode() 18 { 19 parent = null; 20 children = new TreeMap (); 21 } 22 23 public TreeNode(Object value) 24 { 25 this(); 26 setValue(value); 27 } 28 29 public void setValue(Object value) 30 { 31 this.value = value; 32 } 33 public Object 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 key) 48 { 49 return (TreeNode) children.get(key); 50 } 51 52 public void addChild(String key, TreeNode child) 53 { 54 child.setParent(this); 55 children.put(key, child); 56 } 57 58 public TreeNode getOnlyChild() 59 { 60 Iterator 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 getChildren() 68 { 69 return children; 70 } 71 public void setChildren(Map children) 72 { 73 this.children = new TreeMap (children); 74 } 75 76 public boolean isEmpty() 77 { 78 return (getChildren().values().size() == 0); 79 } 80 81 82 public static String printTree(TreeNode node, int level) 83 { 84 Object value = node.getValue(); 85 if (value==null) return ""; 86 87 String caption = value.toString(); 88 String indent = StringUtils.join(" ","",level); 89 String output = indent+caption+" ("+level+")\n"; 90 91 Map children = (Map ) node.getChildren(); 92 Collection values = children.values(); 93 Iterator 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 |