Making Vectors Out Of Mixed-Type Arrays
The chief quality of Vectors is that they hold a single type of object. This is why they are sometimes called “typed arrays”. So what would happen if you wanted to convert an array of mixed-type objects into a vector?
Consider the naive approach:
var arr:Array = [33,"hello",new Point(2,4)]; var vec:Vector.<*> = Vector.<*>(arr); trace(vec);
Which prints…
33,hello,(x=2, y=4)
Tada! Well that was easy. So let’s go a little further and see what happens in a couple of different scenarios. First, let’s ratchet down from the * type to the Object type:
var arr:Array = [33,"hello",new Point(2,4)]; var vec:Vector.<Object> = Vector.<Object>(arr); trace(vec);
This works just as well since all of the elements are also Objects:
33,hello,(x=2, y=4)
How about if we try converting to each element type?
var arr:Array = [33,"hello",new Point(2,4)]; var vecNum:Vector.<Number> = Vector.<Number>(arr); trace(vecNum); var vecStr:Vector.<String> = Vector.<String>(arr); trace(vecStr); var vecPoint:Vector.<Point> = Vector.<Point>(arr); trace(vecPoint);
This seems to convert element-by-element:
33,NaN,NaN 33,hello,(x=2, y=4) Error: TypeError: Error #1034
The error is due to the lack of a built-in conversion from String and Number to Point. This all seems perfectly reasonable to me. The only possible “gotcha” here is if you don’t understand this element-by-element conversion. This doesn’t apply to you though, since you’ve read this article.