Convert Vector.<SomeType> to Array?
Asked Answered
H

2

7

Unfortunately in Actionscript, it seems like support for the Vector class isn't fully there yet. There are some scenarios where I need to convert a Vector into an array (creating an ArrayCollection for example). I thought this would do the trick:

var myVector:Vector.<MyType> = new Vector.<MyType>();

var newArray:Array = new Array(myVector);

Apparently this just creates an array where the first index of the array contains the full Vector object. Is this my only option:

var newArray:Array = new Array(myVector);

for each(var item:MyType in myVector)
{
    newArray.push(item); 
}

I feel like that clutters up the code a lot and I need to do this in a lot of places. The Vector class doesn't implement any kind of interface, so as far as I can tell I can't create a generic function to convert to an array. Is there any way to do this without adding this mess every time I want to convert a Vector to an array?

Hinda answered 9/3, 2011 at 16:54 Comment(1)
most likely answered here already: #1108309Bradway
M
7

There's no easy/fast way to do it, the best solution is to use an utility class like this one:

package {

    public class VectorUtil {

        public static function toArray(obj:Object):Array {
            if (!obj) {
                return [];
            } else if (obj is Array) {
                return obj as Array;
            } else if (obj is Vector.<*>) {
                var array:Array = new Array(obj.length);
                for (var i:int = 0; i < obj.length; i++) {
                    array[i] = obj[i];
                }
                return array;
            } else {
                return [obj];
            }
        } 
    } 
}

Then you just have to update your code to something like this:

var myArray:Array = VectorUtil.toArray(myVector);
Matejka answered 9/3, 2011 at 17:30 Comment(4)
Thanks, sounds like this is the best option. I wish there was a way to pass 'Vector.<*>' as a type to a method.Hinda
That makes me soooo sad. This language has a collection problem. There should be one that works well for everything.Flee
In Apache Flex, there are new classes now for wrapping a vector as an IList: org.apache.flex.collections.VectorList and org.apache.flex.collections.VectorCollectionIcbm
With the Apache Flex SDK you can convert the Vector to a collection with (new VectorList(myVector)).toArray(). This is available from at least Apache Flex SDK v 4.12 if not earlier releases. flex.apache.org/asdoc/org/apache/flex/collections/…Bryophyte
A
3

Paul at Work found a better way to do it.

var newArray:Array = [].concat(myVector);
Apophyllite answered 26/12, 2012 at 15:49 Comment(1)
It doesn't work, which is pointed out in the referenced SO-AnswerPineda

© 2022 - 2024 — McMap. All rights reserved.