0

我有以下 java 代码,它应该在牌组中“洗牌”。卡片组是一个包含卡片对象的数组列表。

private void ShuffleDeck() {
    //Number of cards in deck
    int deckSize = deck.size();

    //Swapping 100 cards
    for(int i = 0; i < 15; i++) {

        //Generating two random card indexes
        int indexA = (int) ((Math.random() * deckSize-1));
        int indexB = (int) (Math.random() * deckSize-1);
        System.out.println(indexA + " " + indexB);

        //Getting objects
        Card cardA = deck.get(indexA);
        Card cardB = deck.get(indexB);

        //Temporaily removing these cards from deck
        deck.remove(cardA);
        deck.remove(cardB);

        //Swapping around the two cards
        deck.add(indexA, cardB);
        deck.add(indexB, cardA);

    }

}

然而,当我运行这个方法时,一些卡片似乎从牌组中“消失”了......关于为什么会这样的任何建议?:)

4

1 回答 1

9

假设deckList<Card>(包括ArrayList等):

public void shuffleDeck() { // please use camelCase method names
    Collections.shuffle(deck);
}

不要重新发明轮子。

于 2013-05-11T18:38:53.037 回答