1 import org.as2lib.core.BasicClass; 2 import org.as2lib.data.holder.Iterator; 3 import org.as2lib.data.holder.List; 4 import org.as2lib.env.except.IllegalArgumentException; 5 import org.as2lib.data.holder.NoSuchElementException; 6 import org.as2lib.env.except.IllegalStateException; 7 8 /** 9 * {@code ListIterator} iterates over lists, that are instances of classes that 10 * implement the {@link List} interface. 11 * 12 * <p>An iterator is quite simple to use. There is one method to check whether there 13 * are more elements left to iterate over {@link #hasNext}, one method to get the 14 * next element {@link #next} and one to remove the current element {@link #remove}. 15 * 16 * <p>Example: 17 * <code> 18 * var list:List = new MyList(); 19 * list.insert("value1"); 20 * list.insert("value2"); 21 * list.insert("value3"); 22 * var iterator:Iterator = new ListIterator(list); 23 * while (iterator.hasNext()) { 24 * trace(iterator.next()); 25 * } 26 * </code> 27 * 28 * <p>Output: 29 * <pre> 30 * value1 31 * value2 32 * value3 33 * </pre> 34 * 35 * @author Simon Wacker 36 */ 37 class org.as2lib.data.holder.list.ListIterator extends BasicClass implements Iterator { 38 39 /** The target to iterate over. */ 40 private var target:List; 41 42 /** The current element index. */ 43 private var i:Number; 44 45 /** 46 * Constructs a new {@code ListIterator} instance. 47 * 48 * @param target the list to iterate over 49 */ 50 public function ListIterator(target:List) { 51 if (!target) throw new IllegalArgumentException("Argument 'target' [" + target + "] must not be 'null' nor 'undefined'.", this, arguments); 52 this.target = target; 53 this.i = -1; 54 } 55 56 /** 57 * Returns whether there is another element to iterate over. 58 * 59 * @return {@code true} if there is at least one element left to iterate 60 * over 61 */ 62 public function hasNext(Void):Boolean { 63 return (this.i < this.target.size() - 1); 64 } 65 66 /** 67 * Returns the next element. 68 * 69 * @return the next element 70 * @throws org.as2lib.data.holder.NoSuchElementException if there is no next element 71 */ 72 public function next(Void) { 73 if (!hasNext()) { 74 throw new NoSuchElementException("There is no more element.", this, arguments); 75 } 76 return this.target.get(++this.i); 77 } 78 79 /** 80 * Removes the currently selected element from this iterator and from the data holder 81 * this iterator iterates over. 82 * 83 * @throws org.as2lib.env.except.IllegalStateException if you try to remove an element 84 * when none is selected 85 */ 86 public function remove(Void):Void { 87 if (this.i < 0) { 88 throw new IllegalStateException("You tried to remove an element before calling the 'next' method. There is thus no element selected to remove.", this, arguments); 89 } 90 this.target.removeByIndex(this.i); 91 } 92 93 }