Using Iterators


After you've defined iterators and collections, you can use the iterators as in the following example, which adds four elements to a UIntCollection object and then uses an iterator to access that data:

var collection:UIntCollection = new UIntCollection(); collection.addElement(1); collection.addElement(20); collection.addElement(5); collection.addElement(15); var iterator:IIterator = collection.iterator(); while(iterator.hasNext()) {    trace(iterator.next()); }


The preceding example uses the iterator to loop through each of the elements of the collection and write it to the debug console. Notice that because the iterator interface is identical for all iterator types, it doesn't matter what concrete type the iterator() method returns. For example, the preceding code would continue to function correctly if you specified ArrayReverseIterator as the parameter for iterator(), thus returning an ArrayReverseIterator instead of an ArrayIterator. The only difference would be the outputwhich would return the collection values in reverse order.

Consider how different this approach is from using the array directly. When you allow direct access to the array, not only do you break encapsulation, you also create code that is specific to the implementation. For example, if you wanted to use a for statement to loop through the elements of an array directly, you would have to change the for statement expressions when you wanted to change how you loop through the array. But when you use the iterators, you don't have to make such changes because the implementation is within the iterator itself.




Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net