Array vs. ArrayCollection in Flex 2
So what’s the difference? Well, the
LiveDocs entry for the ArrayCollection class sums it up pretty well, so here it is:
“The ArrayCollection class is a wrapper class that exposes an Array as a collection that can be accessed and manipulated using the methods and properties of the ICollectionView or IList interfaces. Operations on a ArrayCollection instance modify the data source; for example, if you use the removeItemAt() method on an ArrayCollection, you remove the item from the underlying Array. ”
The first sentence in that explanation is the key: The ArrayCollection class is simply a wrapper around the Array class. So if they’re both Arrays at some level, why is this important? Well, with a standard Array, what you have available to you are the basic methods and properties that you’d expect in any language: push() (for adding an element to the end), pop() (for removing the last element), length (the number of indices), etc. However, the ArrayCollection class provides a suite of immensely convenient “extra” methods that can act on the Array.
For example, say I have an array with the values in the color spectrum:
var spectrumColors:Array = [“red”,”orange”,”yellow”,”green”,”blue”,”indigo”,”violet”];
However, a new theory releases that there’s no such thing as “green,” and mandates that it should be removed from the color spectrum. How would you do it using the Array class? Honestly, it’s not worth getting into the code because it’s a waste of keystrokes. However, there’s a really easy way to do this: Use the ArrayCollection class. The ArrayCollection class extends the
ListCollectionView class. Without getting into the boring details, the ListCollectionView class has a bunch of extremely handy methods for manipulating its elements, namely the addItemAt(), removeItemAt(), and getItemAt() methods. Going back to the example, if the spectrumColors variable is datatyped as being an ArrayCollection, accomodating new theory becomes immensely easier:
var spectrumColors:ArrayCollection = [“red”,”orange”,”yellow”,”green”,”blue”,”indigo”,”violet”];spectrumColors.removeItemAt(spectrumColors.getItemIndex(“green”));
All the code above does is create the spectrumColors variable of type ArrayCollection, and then removes the item from the array based on the returned index value that matches the value “green.” See? Easy. No need to manually loop over the array to find an index or verbose constructs like that.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: