Vector Iterator for Flex

One of the many welcome additions to the Flex 3.4 SDK is the inclusion of the Vector class. Vectors in particular are especially welcome as they provide compile time type safety over what would otherwise not be available when implementing custom solutions, such as a typed collection.

Essentially, Vectors are just typed Arrays. And while not as robust or powerful, Vectors are similar to Generics in C# and Java. When it is known at design time that a collection will only ever need to work with a single type, Vectors can be utilized to provide type safety and also to allow for significant performance gains over using other collection types in Flex.

I recently wanted to convert quite a few typed Array implementations to Vectors, however, the Arrays were being traversed with an Iterator. In order to reduce the amount of client code which needed to be refactored I simply implemented a Vector specific Iterator implementation.

If you are familiar with Iterator Pattern in general, and the Iterator interface in particular, then usage will prove to be very straight forward. You can use the Vector Iterator to perform standard iterations over a Vector. Below is an example of a typical client implementation:

Using an Iterator with a Vector ensures only a linear search can be performed, which proves useful with Vectors as they are dense Arrays. However, one consideration that must be made when using an Iterator with a Vector is that you loose type safety when accessing items in the Vector via iterator.next(). It is because of this I would suggest only using Iterator’s with Vectors to support backwards compatibility when refactoring existing Arrays which are being used with existing Iterators.

The VectorIterator and it’s associated test are available below:
VectorIterator
VectorIteratorTest

{ 1 comment to read ... please submit second! }

  1. public function next() : <T>
    {
    return _vector[_index++];
    }
    Ohhh, dear Adobe, when we get generics?!

{ 0 Pingbacks/Trackbacks }