new Vector - ActionScript 3's Typed Array
Flash Player 10 introduces a new core data type to store lists of data called "Vector". It's almost identical to the vanilla ActionScript array we use today but with the added benefit of being strictly/strongly typed. Strict typing is very beneficial, it helps create error free code while coding and compiling, allows for understandable APIs and best of all, increases code execution performance.
Vector is a top-level class just as Array is so you will not need to import it.
Below is an example of creating a Vector for the int type.
var vec:Vector.<int> = new Vector.<int>();
Notice that we define the type of Vector with the use of the less-than/lower-than brackets.
Here is an extended example using a Vector for holding Sprites.
class Foo {
private var _displayChildren:Vector.<Sprite>;
function Foo() {
_displayChildren = new Vector.<Sprite>;
}
public function addChild(child:Sprite):void {
_displayChildren.push(child);
}
public function removeChild(child:Sprite):void {
var idx:int = _displayChildren.indexOf(child);
_displayChildren.splice(idx,1);
}
public function get numChildren():uint {
return _displayChildren.length;
}
}
If you attempt to add data of the wrong type to a vector, you shall receive a "Type Coercion failed: cannot convert" error. There is however some exceptions, for example if you have a int typed Vector and you try to add a String to it using a push or unshift method, it shall perform an int(string) conversion.
intVec.push("00123")
intVec.push("hello")
trace(intVec) // 123, 0
If you try this however .. intVec[0] = "00123" .. it shall result in a "Implicit coercion of a value of type String to an unrelated type int" error.
The only method Vector didn't pick up from its Array cousin is sortOn. Apart from that, every method from Array is available to use to manipulate Vector.
Vector does introduce something new though, the ability to force a fixed collection length. Below is an example on how to enable fixed length.
// int Vector with fixed length of 5
var vec:Vector.<int> = new Vector.<int>(5, true);
trace(vec.fixed) // true
trace(vec) // 0, 0, 0, 0, 0
While in fixed mode, the methods push/pop/shift/unshift/splice/..etc shall not work and shall result in a "Cannot change the length of a fixed Vector." error.
If you go out of the fixed range using the square bracket notation .. vec[15] = 1 .. you shall find this error "The index 15 is out of range 5.". Posted Thu May 15 2008 12:34:00 | Comments | Post a Comment
Coming Soon
Coming Soon

