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?

Ocelot20
  • 9,720
  • 9
  • 49
  • 96
  • most likely answered here already: http://stackoverflow.com/questions/1107809/as3-how-to-convert-a-vector-to-an-array – jpea Mar 09 '11 at 16:59

2 Answers2

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);
bmleite
  • 26,700
  • 4
  • 69
  • 46
  • Thanks, sounds like this is the best option. I wish there was a way to pass 'Vector.' as a type to a method. – Ocelot20 Mar 09 '11 at 17:36
  • That makes me soooo sad. This language has a collection problem. There should be one that works well for everything. – pseudopeach Sep 01 '11 at 19:46
  • 1
    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.VectorCollection` – vsp Aug 11 '14 at 14:36
  • 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. https://flex.apache.org/asdoc/org/apache/flex/collections/VectorList.html#toArray%28%29 – Ryan Taylor Oct 02 '14 at 12:19
3

Paul at Work found a better way to do it.

var newArray:Array = [].concat(myVector);
Community
  • 1
  • 1