Using Collections

A collection is a group of objects that are stored in memory. Similar to an array, but supporting a more robust set of use cases, collections simplify storing and retrieving objects or even other groups of objects.

The ASDK collections library provides several interfaces and implementation classes that are explored in detail in the Collections section of the user guide. This quick start tutorial focuses on two of the primary interfaces and corresponding implementations that enable storing and retrieving data within a Flash application. These two interfaces are:

The two most common implementations of these interfaces are: asdk.ArrayList (implements Collection) and asdk.HashMap (implements Map).

ArrayList

The example below demonstrates a common usage of an ArrayList:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var groceryCart:asdk.Collection = new asdk.ArrayList();
groceryCart.addItem( "apple" );
groceryCart.addItem( "orange" );
groceryCart.addItem( "grapes" );

if( !groceryCart.containsItem( "bananas" ) )
  trace( "don't forget to buy some bananas" );

var contents:Iterator = groceryCart.iterator();

while( contents.hasNext() )
  {
  var item = contents.getNext();
  trace( item + " is currently in the cart." );
  }

After instantiating an ArrayList instance on line one, several strings are added to the cart. It should be noted that although strings are stored in this example any object can be added to the collection. Line 6 calls the containsItem method to test whether bananas have been added and prints a reminder to the output window. Lastly lines 9-15 demonstrate the use of an iterator which is a common way to traverse all the elements within a collection. Iterators are discussed further within the Data Collections -> Iterators section of the user guide.

HashMap

The next example below demonstrates using a HashMap:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var id1 = 1;
var id2 = 2;
var id3 = 3;

var cache:asdk.Map = new asdk.HashMap();
cache.put( id1, "apple" );
cache.put( id2, "orange" );
cache.put( id3, "grapes" );

var apple = cache.get( id1 );
var orange = cache.get( id2 );
var grapes = cache.get( id3 );

trace( apple );
trace( orange );
trace( grapes );

A HashMap enables developers direct access to data without having to traverse all the stored elements and is especially useful for caching data for maintaining state. The examples above creates an instance of a HashMap on line 5 and populates the map using the ids created in lines 1-3 as the keys and the fruit from the previous examples as values. After the map is populated the values can be retrieved directly using the corresponding keys. It should also be noted that any object type can be used as the key or the value, and typically within an application it is common to store complex values within a map. The HashMap is a powerful data structurethat, until ASDK, has been a glaring omission from the standard ActionScript library.