30 November 2010
General experience with programming in ActionScript 3 is suggested.
Beginning
An array is like a container for grouping together a set of variables. A single array can contain many different values. You can store and access individual values contained in the array (known as the array's elements). You can also work with the values as a group by manipulating the array variable directly. The most common type of array is an indexed array, which uses a number index to select from among the array's values. ActionScript 3 includes two classes that serve as indexed arrays:
If you need to store a collection of values that all have the same data type, the Vector class has a few benefits over the Array class. First of all, because all the elements of a Vector must have the same data type, the ActionScript compiler can check the data type when the code is compiled. Any code that attempts to add or retrieve a value of the wrong type can be caught at compile-time. Data types are also checked at runtime, so in cases where the data type can't be checked at compile-time, it is still checked and the data type restriction is still enforced. In addition to the type-checking benefit, code that uses the Vector class runs significantly faster than equivalent code that uses the Array class—a noteworthy benefit.
This Quick Start describes techniques for creating and working with the Vector class. To learn more about the Array class, see Programming with the Array class.
The following sections describe common tasks for working with Vector objects: creating a Vector instance, adding values to a Vector object, retrieving values from a Vector object, and sorting values in a Vector object.
A Vector object is an indexed array that stores only values of one class. The class that a particular Vector object stores is known as the Vector's base type. You specify a base type when you declare a Vector variable and also when you create a Vector object by calling the Vector class's constructor. As you might expect, the base class specified for a Vector variable must match the base type specified when calling the constructor.
When creating a Vector instance, to specify its base type you add extra information to the Vector class name using a format known as type parameter syntax. For example, the following statement declares a Vector variable named myVector, using type parameter syntax to specify that the Vector stored in myVector can contain only String values:
var myVector:Vector.<String>;
You use the same syntax when you call the Vector class constructor to actually create the Vector object:
myVector = new Vector.<String>();
As a rule, whenever the class name Vector appears in your code, you always use a type parameter with it.
Of course, you can combine the actions of declaring a variable and constructing an instance into one line of code:
var myVector:Vector.<String> = new Vector.<String>();
Although the examples in this Quick Start mostly use simple built-in classes such as String and Number, the base type of a Vector can be any class. This includes custom classes that you define. For example, suppose your code defines a class named MyClass. In that case, the following code is valid and creates a Vector object whose elements must all be MyClass instances:
var v:Vector.<MyClass> = new Vector.<MyClass>();
The Vector class constructor has two optional parameters that enable you to specify characteristics of your Vector instance. The first parameter is the length parameter. By default, a Vector is empty when it is created (it has 0 elements). However, if you pass a value for the length parameter, the Vector is instantiated with the specified number of elements already created:
var myVector:Vector.<String> = new Vector.<String>(7); // myVector is created with 7 elements
Prespecifying the size of the Vector is faster than creating elements one at a time, so if you know ahead of time how many elements a Vector will contain, it is better to provide a length parameter value. If the base type of the Vector is Boolean or one of the numeric types (Number, int, uint), each element is prepopulated with the default value for its data type (false for Boolean, 0 for numeric types). Otherwise, each element initially contains the value null.
Another feature of Vector objects is that they can be fixed-length, meaning you can change values but can't change the total number of values by adding or removing them. By default, a Vector instance is not fixed-length. To create a fixed-length Vector, specify true for the second parameter (the fixed parameter) of the Vector class constructor:
var myVector:Vector.<String> = new Vector.<String>(7, true); // myVector's length is fixed to 7 elements
Note: You can change the value of a Vector object's fixed property at any time to make a Vector fixed-length or remove the fixed-length restriction from a Vector:
myVector.fixed = false; // myVector's length is no longer fixed
Adding a value to a Vector object is similar to adding a value to an Array object, with one additional restriction. A Vector object must have a value (or null) for every element. In other words, you can't add a value at index position 4 unless the Vector already has values at indices 0–3. In practice, this means that to add a new element to a Vector, you must add it at the index position equal to the Vector object's length property. (Because the first element of a Vector has index 0, the length property's value is always one greater than the index of the last element in the Vector.) The following code listing demonstrates this technique:
var names:Vector.<String> = new Vector.<String>();
// ... assume some elements are added ...
// Add an element to the end of the Vector
names[names.length] = "Bob";
In addition to using the array access ([]) operator to add a value to a Vector object, you can use the Vector object's push() or unshift() methods to add elements to the Vector. Just as with the Array class, the push() method creates a new element after the last element in a Vector, and the unshift() method creates a new element at index 0 of the Vector (and shifts all the existing elements one index position higher):
names.push("Harold"); // adds the value "Harold" to the end of the Vector
names.unshift("Fred"); // adds the value "Fred" to the start of the Vector
These methods have the additional advantage that you can pass multiple values as arguments to the method, and all the values are added to the Vector at once. However, there is a consequence of this flexibility. When you use the push() or unshift() method to add a value to a Vector, the compiler isn't able to check that the data types of the values match. Consequently, any code that uses push() or unshift() to add a value of the wrong type to the Vector won't be caught until you run the code.
Retrieving a value from a Vector object is identical to retrieving a value from an Array object. To retrieve the value of an element at a particular index, you just use the array access ([]) operator to specify the index of the element you want:
var name1:String = names[0];
Using the array access ([]) operator retrieves the value, but doesn't remove it from the Vector object. To retrieve a value and remove it from the Vector, use the pop() method (which removes the final element) or the shift() method (which removes element 0 and shifts all the elements down one position):
var finalName:String = names.pop(); // removes the last value from the Vector
var firstName:String = names.shift(); // removes the first value from the Vector
Most parts of working with a Vector object are identical to working with an Array object. One way that they're notably different is in sorting the elements of a Vector. The Vector class only has one method for sorting values: the sort() method. The sort() method doesn't modify the original Vector object. Instead, it returns a new Vector with the same base type, containing the values in sorted order.
When you use the Vector class's sort() method, there is no default sorting behavior, not even for basic data types such as Number or String. Because of this, anytime you use the sort() method, you specify a custom sorting function that defines the sorting logic. For example, in the following code a Vector of Number objects is sorted using the sort() method. In this case, the code performs a basic numeric sort; lesser numbers are placed before greater numbers. The function that defines the sorting behavior, named sortNumbers(), is passed as an argument to the sort() method call. As Flash Player sorts each number, it calls the sortNumbers() function, passing in two numbers being compared, and the result determines the final sort order:
var numberVector:Vector.<Number> = new Vector.<Number>();
numberVector.push(2, 17, 3.6, 4.4, 29, -34, 0.09235);
trace(numberVector); // output: 2,17,3.6,4.4,29,-34,0.09235
var sortedVector:Vector.<Number> = numberVector.sort(sortNumbers);
trace(sortedVector); // output: -34,0.09235,2,3.6,4.4,17,29
function sortNumbers(x:Number, y:Number):Number
{
if (x < y)
{
return -1;
}
else if (x > y)
{
return 1;
}
else
{
return 0;
}
}
You can define a sorting function for any data type. For example, the following code sorts a Vector of Person objects by last name, then first name (it assumes there is a Person class that has firstName and lastName properties):
var personVector:Vector.<Person> = new Vector.<Person>();
personVector[0] = new Person("Bob", "Smith");
personVector[1] = new Person("Harold", "Johnson");
personVector[2] = new Person("Barbara", "Smith");
personVector[3] = new Person("Arnold", "Anderson");
personVector[4] = new Person("Margaret", "Wooster");
// output:[Smith,Bob],[Johnson,Harold],[Smith,Barbara],[Anderson,Arnold],[Wooster,Margaret]
trace(personVector);
var sortedVector:Vector.<Person> = personVector.sort(sortPeople);
// output:[Anderson,Arnold],[Johnson,Harold],[Smith,Barbara],[Smith,Bob],[Wooster,Margaret]
trace(sortedVector);
function sortPeople(x:Person, y:Person):Number
{
// sort by last name
var lastNameSort:Number = sortStrings(x.lastName, y.lastName);
if (lastNameSort != 0)
{
return lastNameSort;
}
else
{
// if the last names are identical, sort by first name
return sortStrings(x.firstName, y.firstName);
}
}
function sortStrings(x:String, y:String):Number
{
if (x < y)
{
return -1;
}
else if (x > y)
{
return 1;
}
else
{
return 0;
}
}
You can download the sample archive, programming_with_vector.zip, from the top of this page. This sample includes the following files:
To test each application, open the FLA file and choose Control > Test Movie.
You can find all the details of the Vector class in the following entries in the ActionScript 3.0 Reference for the Adobe Flash Platform: