1 56 57 package org.jdom; 58 59 import java.util.*; 60 import org.jdom.Content; 61 import org.jdom.Element; 62 import org.jdom.Parent; 63 64 72 class DescendantIterator implements Iterator { 73 74 private Iterator iterator; 75 private Iterator nextIterator; 76 private List stack = new ArrayList(); 77 78 private static final String CVS_ID = 79 "@(#) $RCSfile: DescendantIterator.java,v $ $Revision: 1.5 $ $Date: 2004/02/27 11:32:57 $ $Name: $"; 80 81 86 DescendantIterator(Parent parent) { 87 if (parent == null) { 88 throw new IllegalArgumentException ("parent parameter was null"); 89 } 90 this.iterator = parent.getContent().iterator(); 91 } 92 93 98 public boolean hasNext() { 99 if (iterator != null && iterator.hasNext()) return true; 100 if (nextIterator != null && nextIterator.hasNext()) return true; 101 if (stackHasAnyNext()) return true; 102 return false; 103 } 104 105 110 public Object next() { 111 if (!hasNext()) { 112 throw new NoSuchElementException(); 113 } 114 115 if (nextIterator != null) { 119 push(iterator); 120 iterator = nextIterator; 121 nextIterator = null; 122 } 123 124 while (!iterator.hasNext()) { 126 if (stack.size() > 0) { 127 iterator = pop(); 128 } 129 else { 130 throw new NoSuchElementException("Somehow we lost our iterator"); 131 } 132 } 133 134 Content child = (Content) iterator.next(); 135 if (child instanceof Element) { 136 nextIterator = ((Element)child).getContent().iterator(); 137 } 138 return child; 139 } 140 141 147 public void remove() { 148 iterator.remove(); 149 } 150 151 private Iterator pop() { 152 int stackSize = stack.size(); 153 if (stackSize == 0) { 154 throw new NoSuchElementException("empty stack"); 155 } 156 return (Iterator) stack.remove(stackSize - 1); 157 } 158 159 private void push(Iterator itr) { 160 stack.add(itr); 161 } 162 163 private boolean stackHasAnyNext() { 164 int size = stack.size(); 165 for (int i = 0; i < size; i++) { 166 Iterator itr = (Iterator) stack.get(i); 167 if (itr.hasNext()) { 168 return true; 169 } 170 } 171 return false; 172 } 173 } 174 | Popular Tags |