The asdk.Iterator
interface provides three methods for traversing and removing the elements of a collection. Every
implementation of the Collection interface provides an iterator()
method that returns an implmentation of asdk.Iterator
.
Continuing with the previous example the code below demonstrates how to retrieve data from the groceryCart variable which is an ArrayList:
1 2 3 4 5 6 |
... |
Instead of relying on an index, this example traverses all of the elements within the ArrayList using an Iterator. Although the code above is functionally equivalent to the index-based example, it provides a cleaner way to access the elements in a list.
Since a HashMap contains key/value pairs, the iterator method for this class can also take an optional argument to retreive a key iterator. The example below demonstrates using the iterator method both with this optional parameter and without it to retrieve the keys and values of a map respectively. Note below that the default behavior of this method when an argument is not supplied is to return an iterator that traverses the values within the HashMap.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var id1 = 1; |
In addition, the Map interface, which HashMap implements, surfaces ease-of-use APIs for retrieving a reference to the respective
iterators available including the self describing methods: getKeysIterator
and getValuesIterator
.
A more straight forward method of retrieving data from a LinkedList involves using an Iterator. Using this technique, a developer
can use a common interface to access the data, and not be concerned with the underlying implementation of the class. In addition,
as demonstrated below, the LinkedList class has a convenience method dataIterator
(line 9) that further simplifies the code by
returning the data in the Iterator instead of LinkedListItems.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var rainbowColors:LinkedList = new LinkedList(); |
Note that using the Iterator pattern above, the code to retrieve items from a LinkedList is nearly identical
to the code for accessing data in an ArrayList as in the first example above. The only difference in this example
is the call on line 9 to tbe dataIterator
method that allows for direct access to the data within the list.
Running the example above yields the following lines in the output window of the Flash IDE.
1 2 3 4 5 6 |
purple |