How do you access/modify specific elements in a List in Haxe?

Viewed 85

I am new to Haxe and I am looking for an equivalent data structure to Java's ArrayList, which is resizable and indexed. Haxe's List only allows access to its first and last element.

This is my use case:

I have a class Deck which represents a deck of 52 playing cards. The objects of type Card are stored in a List<Card>.

class Deck {
    var cards:List<Card>;

    public function new() {}

    public function init() {
        cards = new List<Card>();
        for (i in 1...5) { // iterate over suits
            for (j in 1...14) { // iterate over values
                cards.add(new Card(j, SuitFunctions.toSuit(i)));
            }
        }
    }
}

Now I want to implement a function shuffle which shuffles the cards.

public function shuffle() {
    var j:Int, k:Int;
    var c:Card;
    for (i in 1...1000000) {
        j = Std.random(cards.length);
        k = Std.random(cards.length);
        c = getCardAt(j);
        setCardAt(j, getCardAt(k));
        setCardAt(k, c);
    }
}

But Lists in Haxe are not indexed. How would I implement the functions getCardAt(Int) and setCardAt(Int, Card)? This is what the signatures should look like:

function getCardAt(i:Int):Card {
    // ToDo
    return new Card(0, Suit.ERROR);
}

function setCardAt(i:Int, c:Card) {
    // ToDo
}

Alternatively, is there a different data structure that fits this scenario better? Are for example Arrays resizable and indexed in Haxe?

Best regards.

1 Answers

I am looking for an equivalent data structure to Java's ArrayList, which is resizable and indexed.

Array is what you want, they are "dynamic arrays", so they resize automatically.

List is a linked list, and it's not used much.

Related