1 4 5 package polyglot.util; 6 7 import java.util.Iterator ; 8 import java.util.Collection ; 9 10 19 public final class TransformingIterator implements Iterator { 20 public TransformingIterator(Iterator iter, Transformation trans) { 21 this(new Iterator []{iter}, trans); 22 } 23 24 public TransformingIterator(Collection iters, Transformation trans) { 25 index = 0; 26 backing_iterators = (Iterator []) iters.toArray(new Iterator [0]); 27 transformation = trans; 28 if (backing_iterators.length > 0) 29 current_iter = backing_iterators[0]; 30 findNextItem(); 31 } 32 33 public TransformingIterator(Iterator [] iters, Transformation trans) { 34 index = 0; 35 backing_iterators = (Iterator []) iters.clone(); 36 transformation = trans; 37 if (iters.length > 0) 38 current_iter = iters[0]; 39 findNextItem(); 40 } 41 42 public Object next() { 43 Object res = next_item; 44 if (res == null) 45 throw new java.util.NoSuchElementException (); 46 findNextItem(); 47 return res; 48 } 49 50 public boolean hasNext() { 51 return next_item != null; 52 } 53 54 public void remove() { 55 throw new UnsupportedOperationException ("TransformingIterator.remove"); 56 } 57 58 private void findNextItem() { 60 while (current_iter != null) { 61 inner_loop: 62 while (current_iter.hasNext()) { 63 Object o = current_iter.next(); 64 Object res = transformation.transform(o); 65 if (res == Transformation.NOTHING) 66 continue inner_loop; 67 next_item = res; 68 return; 69 } 70 index++; 71 if (index < backing_iterators.length) { 72 current_iter = backing_iterators[index]; 73 } else { 74 current_iter = null; 75 } 76 } 77 next_item = null; 78 } 79 80 Object next_item; 86 Iterator current_iter; 87 int index; 88 Iterator [] backing_iterators; 89 Transformation transformation; 90 } 91 92 93 | Popular Tags |