您如何将获胜者所比较的卡片加进去。我有并发修改错误。我正在尝试将阵列桩添加到优胜者阵列列表中,但出现错误。

import java.util.ArrayList;

public class Deck {
    ArrayList<Card> deck = new ArrayList<Card>();
    ArrayList<Card> player1 = new ArrayList<Card>();
    ArrayList<Card> player2 = new ArrayList<Card>();
    ArrayList<Card> pile = new ArrayList<Card>();
    boolean winner;

    public Deck(){

    }
    public void createDeck(){
        for(int i =0; i<4; i++){
            for(int j =1; j<15;j++){
                if(i==0) deck.add(new Card("Spades", j));
                if(i==1) deck.add(new Card("Hearts", j));
                if(i==2) deck.add(new Card("Clubs", j));
                if(i==3) deck.add(new Card("Diamonds",j));

            }
        }
    }
    public void splitDeck(){
        for(int i = 0; i< 52;i++){
            int r = (int) (Math.random()*(51-i));
            if(i%2==0){
                player1.add(deck.get(r));
            }
            else{
                player2.add(deck.get(r));
            }
            deck.remove(r);
        }

    }
    public int [] war(){

        int[]score = {0,0};

        for(Card c : player1){
            int x = player1.indexOf(c);
            if(c.getValue() > player2.get(x).getValue()){
                winner = true;
                score[0]++;
                pile.add(player1.get(x));
                pile.add(player2.get(x));
                distributeCards();
            }
            else if(c.getValue() <player2.get(x).getValue()) score[1]++;
            distributeCards();
        }

        return score;
    }

    public void distributeCards(){

            if(winner==true){
                for(int i = 0; i<pile.size(); i++){
                    player1.add(pile.get(i));
                }
            }
            else{
                for(int i = 0; i<pile.size(); i++){
                    player2.add(pile.get(i));
                }
            }
        }


    public String warGame(){
        String print= "";
        for(Card c : player1){
            int x = player1.indexOf(c);
            if(c.getValue() > player2.get(x).getValue()){

                print+= "\n"+"Player1 won";
            }
            else if(c.getValue() <player2.get(x).getValue())
                print+="\n"+"Player2 won";

            else if(c.getValue() ==player2.get(x).getValue())
                print+= "\n"+"Its a tie";
        }

        return print;

    }
}


错误消息是...

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at Deck.war(Deck.java:41)
    at War.main(War.java:7)

最佳答案

在迭代数组列表war()的内部player1中,您正在调用修改distributeCards()player1。您不能在迭代时更改列表-这就是为什么要获取ConcurrentModificationException的原因(请阅读docs以获得更多说明)。

解:
player1复制到tmp列表-并仅在完成遍历player1之后修改该tmp列表-将tmp分配给player1。 (相同的逻辑适用于player2

09-28 05:16