1 25 26 package net.killingar.forum.internal; 27 28 import net.killingar.Stack; 29 30 import java.util.Iterator ; 31 32 public class TreeIterator implements Iterator 33 { 34 Stack stack = new Stack(); 35 int index = 0; 36 37 class StackItem implements Iterator 39 { 40 int index = 0; 41 ParentIDItemTreeNode node; 42 43 StackItem(ParentIDItemTreeNode inNode) 44 { 45 node = inNode; 46 } 47 48 public boolean hasNext() 49 { 50 if (node.subnodes == null) 51 return false; 52 53 if (index == node.subnodes.size()) 54 return false; 55 56 return true; 57 } 58 59 public Object next() 60 { 61 return node.subnodes.get(index++); 62 } 63 64 public void remove() 65 { 66 throw new UnsupportedOperationException (); 67 } 68 } 69 70 ParentIDItemTreeNode nextNode; 71 72 public TreeIterator(ParentIDItemTreeNode inNode) 73 { 74 this(inNode, true); 75 } 76 77 public TreeIterator(ParentIDItemTreeNode inNode, boolean skipFirst) 78 { 79 nextNode = inNode; 80 stack.push(new StackItem(inNode)); 81 82 if (skipFirst && hasNext()) 83 next(); 84 } 85 86 public boolean hasNext() 87 { 88 return nextNode != null; 89 } 90 91 public Object next() 92 { 93 if (nextNode == null) 94 throw new IllegalStateException (); 95 96 ParentIDItemTreeNode ret = nextNode; 97 98 StackItem i = (StackItem)stack.peek(); 99 100 index++; 101 102 while (!i.hasNext() && stack.size() != 1) 103 { 104 stack.pop(); 105 i = (StackItem)stack.peek(); 106 } 107 108 if (i.hasNext()) 109 { 110 nextNode = (ParentIDItemTreeNode)i.next(); 111 112 if (nextNode.subnodes != null) 113 { 114 stack.push(new StackItem(nextNode)); 115 116 if (!((StackItem)stack.peek()).hasNext()) 117 throw new RuntimeException ("shouldn't have pushed! "+nextNode.subnodes.size()); 118 } 119 } 120 else 121 { 122 nextNode = null; 123 } 124 125 127 return ret; 128 } 129 130 public void remove() 131 { 132 throw new UnsupportedOperationException (); 133 } 134 } 135 | Popular Tags |