Vector-ActionScript 3 中的强类型数组

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.

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.