Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Vector.<SomeType> to Array?

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?

like image 722
Ocelot20 Avatar asked Mar 09 '11 16:03

Ocelot20


1 Answers

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);
like image 184
bmleite Avatar answered Sep 30 '22 11:09

bmleite