How to initialize an array with a given size in haxe

I was wondering if there is a way to initialize the array to a given size n(as in the C ++ constructor std::vectoror @steve richey below, without breaking the hint element)?

My thought was to drop the ndefault elements into the newly created array, but even this seems impossible, because there seems to be no way to define the default element, as shown in the original question below:

- original question -

I am trying to write a static function in haxe (starting with 3.0.1) to create an array of a given size n containing types of arbitrary type T. I could not figure out how to use Type.createEmptyInstance () correctly for this. The closest I can get is:

class Main {
    static public function new_array<T>(n:Int):Array<T> {
    var a:Array<T> = new Array<T>();
    var t:T = new T(); //not OK
    for (i in 0...n)
        a.push(Type.createEmptyInstance(Type.getClass(t)));
    return a;
}
    static public function main() {
            var a:Array<Int> = new_array(3);
    }
}

new_array() . : Main.hx:4: characters 12-19 : Only generic type parameters can be constructed.

, ​​ T.

,

+4
3

Haxe . , , .

class Test {
    static function main(){
        var vector = new haxe.ds.Vector(5); // Starting Length
        vector[0] = "zero";
        vector[3] = "three";
        // vector[7] = "seven"; // Will cause Runtime error on some platforms! 
        for ( val in vector ) {
            trace( val );
            // "zero"
            // null
            // null
            // "three"
            // null
        }
    }
}

, - "", . (, Flash), , . (, JS) , .. , :)

, - :

var arr = [];
arr[0] = "zero";
arr[8] = "eight";

1-7 "null", - - .

:

+5

:

@:generic static public function new_Array<T>( ArrayType:T, Length:Int ):Array<T> {
    var empty:Null<T> = null;
    var newArray:Array<T> = new Array<T>();

    for ( i in 0...Length ) {
        newArray.push( empty );
    }

    return newArray;
}

, :

var myArray:Array<Int> = new_Array( 1, 25 );

, 1 , Int, , - , , , .

+1

here's an easy way if you need to set the length of the array, even if there is no data in it:

    var myArray:Array<String> = new Array<String>();   //in this case array of strings
    myArray[5] = null;                                 //in this case setting length to 6

elements 0 - 4 are not set (if you debug them, they are not specified), but they will be considered zero.

0
source

All Articles