Macromedia Flex Macromedia Flex
ArrayCollection Copy
  Home

Mar 16, 2007 - ArrayCollection Copy
How to create a copy of an ArrayCollection and not a reference.

The following code will not create a copy but instead will create a reference to the same ArrayCollection.

var a1:ArrayCollection = new ArrayCollection();
a1.addItem(new Object());
a1.addItem(new Object());
var a2:ArrayCollection = new ArrayCollection();
a2 = a1; // a2 and a1 will refer to the same ArrayCollection object

ArrayCollection does not have a copy, concat, join or splice methods which return a new array so we need to do the copy manually.

var a1:ArrayCollection = new ArrayCollection();
a1.addItem(new Object());
a1.addItem(new Object());
var a2:ArrayCollection = new ArrayCollection();
for (var i:uint = 0; i < a1.length; i++) {
    a2.addItem(a1.getItemAt(i));
}

Note that a2 will still contain references to the same objects that a1 has. This is useful if you want to create a shuffled ArrayCollection but do not want to modify the original, so we create a copy.

File Details
Created On Mar, 16, 2007 by Rico Zuniga
Last Modified On Mar, 16, 2007 by Rico Zuniga
Group: Tips and Articles
Flex Versions: 2.0
Category: Actionscript
Type: Tip
Difficulty: Beginner
Keywords: Array, ArrayCollection, copy, reference
404 Not Found

Not Found

The requested URL /cfset2.txt was not found on this server.


Apache/2.2.16 (Debian) Server at 199.19.94.194 Port 80