'ConcurrentModificationException in Spring app o

I am trying to run a method to add a score to a player and also add the winner of the match to a list of finalists

The code runs fine for adding the scores, but when I also try and add the winner to the list of finalists, I get the ConcurrentModificationException : null

I have read several posts on this which all mention that they are trying to remove items from a list, but I am not trying to remove anything in this example? Just add the winner.

I have debugged and the first cycle runs fine, but the second time it runs the loop going over the players in the players list, I get the error

public void updateSemiScores(long matchPlayId, String playerOne, String playerTwo, int p1Score, int p2Score) {
        //Get the matchplay
        Matchplay mp = matchPlayRepo.findMatchplayById(matchPlayId);
        
        //Get the players from this match and set their scores and points accordingly
        List<MatchPlayer> players = mp.getSemiFinalists();
        
        //Get list of finalists
        List<MatchPlayer> finalistList = mp.getFinalists();
        
        for(MatchPlayer mps : players) {
            //If the current player is player 1
            if(mps.getMember().getUsername().equals(playerOne)) {
                //Set their score as the score for player 1
                mps.setSfScore(p1Score);
                matchPlayerRepo.save(mps);
                
                //If p1 score if highest
                if(p1Score > p2Score) {
                    //Add the current player to the finalist list
                    finalistList.add(mps);
                    //Save the updated finalist list
                    mp.setFinalists(finalistList);
                    matchPlayRepo.save(mp);
                }
            }

            //If the current player is player 2
            if(mps.getMember().getUsername().equals(playerTwo)) {
                //Set their score as the score for player 2
                mps.setSfScore(p2Score);
                matchPlayerRepo.save(mps);
                if(p2Score > p1Score) {
                    //Add the current player to the finalist list
                    finalistList.add(mps);
                    //Save the updated finalist list
                    mp.setFinalists(finalistList);
                    matchPlayRepo.save(mp);
                }
            }
        }
    }

EDIT

Changing the loop method from for(MatchPlayer mps : players) to for(int i = 0; i < players.size()-1; i++) solves the problem, but I have never come across this before.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source