Another great new feature of AS3 and Flash Player 10 is the Vector Class. Vectors are a lot like Arrays, in that they’re unsorted lists which can hold values/variables – with one caveat – they can only hold one type of variable. Vectors are otherwise known as typed Arrays or strict lists. While normal Arrays can hold multiple types of variables, Vectors can hold a single type of variable, oh and did I mention they can be fixed?
This is how we normally declare Arrays:
var array:Array = new Array(); //or var array:Array = ;
And/so this is how we declare Vectors:
var vector:Vector.<uint> = new Vector.<uint>(); //or var vector:Vector.<uint>; vector = new Vector.<uint>();
This kind of behavior can greatly increase the performance of the script running in the AVM. With no extra conditioning or checksumming in memory to access the elements, this strictly typed “Array” can perform all your list tasks with great ease. Also, we’re not limited to casting our vectors to primitive types like Numbers and Strings, you can cast to any custom type you want. However, the base types must match exactly, inherited types are not allowed either. For example, even though Sprite is a subclass of DisplayObject, it won’t compile. See example below.
//Won't compile var vector:Vector.<DisplayObject> = new Vector.<Sprite>(); //Will compile var vector:Vector.<Sprite> = new Vector.<Sprite>();
This type of variable declaration is obviously a little unorthodox, but it has its reasons… At this point, we should only keep in mind that it’s known as “postfix type parameter syntax”.
If you’re like me, you like to shorthand your declarations whenever possible, so If you used to do.
var array:Array = [1, 2, 3, 4, 5, 6, 7];
you can equally do
var vector:Vector.<uint> = Vector.<uint>([1, 2, 3, 4, 5, 6, 7]);
Notice the absence of the “new” keyword, for all obvious reasons, and if it’s not obvious to you, it’s because the constructor will return a new instance anyway.
As mentioned earlier, Vectors are a lot like Arrays, you can pop, push, shift, unshift, sort… to manipulate the lists elements. Just like an Array, when passed as the first argument to the Vector constructor, Vectors can be initialized with a specific size or length. Additionally, when passed as a Boolean in the second argument, Vectors can be fixed, sort of like a constant length, so you have to be careful not to go over board/bounds with your pops and pushes. By default, the length is set to zero or unlimited and they’re not fixed rather set to false.
/* Will throw a RangeError. I'm declaring a variable called vector, with 10 elements and setting fixed to true. If fixed were set to falsewe wouldn't get any errors, as we are not limited to the number of elements allowed. */ var vector:Vector.<uint> = new Vector.<uint>(10, true); vector.push(1);
For more info on Vectors, check out the Adobe site on it.