Google analytics code

Tuesday, April 13, 2010

Flex / ActionScript: Copy an ArrayCollection

While working with an ArrayCollection I ran into a issue. It seems when you set one ArrayCollection equal to another they share memory space. This can cause issues when you perform any operation that will alter the internal array.

var arrayCollection1:ArrayCollection = new ArrayCollection([1,2,3,4,5]);
var arrayCollection2:ArrayCollection = arrayCollection1;

trace("arrayCollction1: " + arrayCollection1.toString());
trace("arrayCollction2: " + arrayCollection2.toString());

arrayCollection1.removeItemAt(0);

trace("arrayCollction1: " + arrayCollection1.toString());
trace("arrayCollction2: " + arrayCollection2.toString());
Output:
arrayCollection1: 1,2,3,4,5
arrayCollection2: 1,2,3,4,5

arrayCollection1: 2,3,4,5
arrayCollection2: 2,3,4,5

The simple solution for this is to always create a new ArrayCollection for the target using the toArray method from the source.

var arrayCollection1:ArrayCollection = new ArrayCollection([1,2,3,4,5]);
var arrayCollection2:ArrayCollection = new ArrayCollection(arrayCollection1.toArray());

trace("arrayCollection1: " + arrayCollection1.toString());
trace("arrayCollection2: " + arrayCollection2.toString());

arrayCollection1.removeItemAt(0);

trace("arrayCollection1: " + arrayCollection1.toString());
trace("arrayCollection2: " + arrayCollection2.toString());
Output: 
arrayCollection1: 1,2,3,4,5
arrayCollection2: 1,2,3,4,5

arrayCollection1: 2,3,4,5
arrayCollection2: 1,2,3,4,5

Those post is based on findings from this blog post.