Cloning Arrays; Advanced Topics - Adobe FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0 Manual

Programming actionscript 3.0
Table of Contents

Advertisement

Cloning arrays

The Array class has no built-in method for making copies of arrays. You can create a shallow
copy of an array by calling either the
shallow copy, if the original array has elements that are objects, only the references to the
objects are copied rather than the objects themselves. The copy points to the same objects as
the original does. Any changes made to the objects are reflected in both arrays.
In a deep copy, any objects found in the original array are also copied so that the new array does
not point to the same objects as does the original array. Deep copying requires more than one
line of code, which usually calls for the creation of a function. Such a function could be
created as a global utility function or as a method of an Array subclass.
The following example defines a function named
algorithm is borrowed from a common Java programming technique. The function creates a
deep copy by serializing the array into an instance of the ByteArray class, and then reading the
array back into a new array. This function accepts an object so that it can be used with both
indexed arrays and associative arrays, as shown in the following code:
import flash.utils.ByteArray;
function clone(source:Object):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}

Advanced Topics

Extending the Array class
The Array class is one of the few core classes that is not final, which means that you can create
your own subclass of Array. This section provides an example of how to create a subclass of
Array and discusses some of the issues that can arise during the process.
or
concat()
slice()
clone()
methods with no arguments. In a
that does deep copying. The

Advanced Topics

243

Advertisement

Table of Contents
loading

This manual is also suitable for:

Flex

Table of Contents