Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Flash Developer Center /

Programming with the Vector class

by H. Paul Robertson

H. Paul Robertson
  • Blog

Content

  • Creating a Vector instance
  • Predefining a Vector's length
  • Creating a fixed-length Vector
  • Adding values to a Vector object
  • Retrieving values from a Vector object
  • Sorting values in a Vector object
  • Using the sample files
  • Where to go from here

Modified

30 November 2010

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScript arrays Flash Professional

Requirements

Prerequisite knowledge

General experience with programming in ActionScript 3 is suggested.

User level

Beginning

Required products

  • Flash Professional (Download trial)

Sample files

  • programming_with_vector.zip (25 KB)

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:

  • Array class: An indexed array whose elements can be values of any type, including mixing types of values in the same array.
  • Vector class: An indexed array whose elements must all be instances of the same class. The Vector class is available with Adobe Flash Player 10 and later.

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.

Creating a Vector instance

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>();

Predefining a Vector's length

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.

Creating a fixed-length Vector

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 values to a Vector object

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 values from a Vector object

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

Sorting values in a Vector object

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; } }

Using the sample files

You can download the sample archive, programming_with_vector.zip, from the top of this page. This sample includes the following files:

  • SortVectorOfNumber.fla and SortVectorOfNumber_CS5.fla (Flash CS5 version): A Flash Professional file demonstrating sorting Number values in a Vector, as described in "Sorting values in a Vector instance" in this Quick Start.
  • SortVectorOfObject.fla and SortVectorOfObject_CS5.fla (Flash CS5 version): An example demonstrating sorting custom objects in a Vector, as described in "Sorting values in a Vector instance" in this Quick Start.
  • Person.as: Source code for the Person class, referenced in SortVectorOfObject.fla.

To test each application, open the FLA file and choose Control > Test Movie.

Where to go from here

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:

  • Vector class
  • Vector.<T>() conversion function

Related Flash Quick Starts

  • Embedding fonts
  • Loading images and Library assets in Flash with ActionScript 3
  • Loading and saving local files with the FileReference class
  • Event handling
  • Display list programming
  • Creating a simple ActionScript 3 class
  • Working with symbols and the Document class
  • Programming with arrays

More Like This

  • Embedding fonts
  • Event handling in ActionScript 3
  • Working with symbols and the Document class
  • Display list programming in ActionScript 3
  • Using ActionScript 3 drawing commands
  • Displaying images with the TileList component
  • Creating a simple ActionScript 3 class
  • Creating, populating, and resizing the DataGrid component
  • Customizing and sorting the DataGrid component
  • Loading images and Library assets with ActionScript 3

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement