Cloning ArrayCollection

Posted: 14/04/09

An image of Cloning ArrayCollection

There are plenty of occasions where you might want to be able to create an exact clone of a complex/nested data objects, without your new object simply referencing the old one's values. To do this, you need to force the creation of new values and references. Depending on the complexity of the data stored, this will be achieved through shallow or deep copying:

Shallow Copy

Fine if your collection only contains values and references that can be shared/reused around the app:

var newAC:ArrayCollection = new ArrayCollection( originalAC.source ) );

Deep Copy

Heavier going; but as well as creating cloned values, it creates new references (pointers) for everything too. Only really necessary if you don't want your new object to hold the same object references that your old one did:

private function clone( source:Object ) :*


var myBA:ByteArray = new ByteArray();

myBA.writeObject( source );

myBA.position = 0;

return( myBA.readObject() );


var newAC:ArrayCollection = new ArrayCollection( clone( originalAC.source ) );

The clone method in the code above can be used for cloning just about any object (including deep copying of ByteArray), and would make a good utility method in any custom framework (both within or outside of the Flex framework). Please note that readObject() will not work with Flash DisplayObjects; however, it will work with complex objects derived from simple types.

The Flex frameworks includes the ObjectUtil that allows you to perform a clean copy using the copy() method.

var myAC:ArrayCollection = new ArrayCollection( ObjectUtil.copy( originalAC.source ) as Array );

Acknowledgement: Thanks to Daniel Jarvis for sharing some of his thoughts on this subject with me.

ArrayCollection documentation

Keywords for this post: clone, duplicate, copy, ArrayCollection, Array, data, objects, actionscript 3, flex, bytearray