ConcurrentModificationException

Discussion in 'Plugin Development' started by Starfire1337, Aug 9, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    Starfire1337

    I currently have a HashMap with <String, Integer>, where String is a player name, and Integer is the arena Id. This HashMap is used to associate players with what specific arena they are in. I also have a function known as winGame(), where a player wins the game. During this function, I need to loop through all players currently in the arena and take them out of the arena.

    Code:java
    1.  
    2. public static void winGame(int arena, Player pl) {
    3. if(GameState.getState(arena) == GameState.LOBBY || GameState.getState(arena) == GameState.COUNTDOWN) {
    4. return;
    5. }
    6. MessageManager.winGame(pl); //broadcasts a message to all players in the arena
    7. for(Map.Entry<String, Integer> entry : players.entrySet()) {
    8. if(entry.getValue().equals(arena)) {
    9. Player p = Bukkit.getPlayer(entry.getKey());
    10. sbMan.updateScoreboard(p.getName(), 0); //removes the scoreboard
    11. removePlayer(p); //removes the player from the game
    12. }
    13. }
    14. }


    Code:java
    1.  
    2. public static void removePlayer(Player p){
    3. if(!ArenaManager.getManager().isInGame(p)) {
    4. MessageManager.sendMessage(p, ChatColor.GRAY + "You are not currently in a game!");
    5. return;
    6. }
    7. Arena a = null;
    8. for(Arena arena : arenas){
    9. if(arena.getPlayers().contains(p.getName())){
    10. a = arena;
    11. }
    12. }
    13. if(a == null || !a.getPlayers().contains(p.getName())){
    14. MessageManager.sendMessage(p, ChatColor.GRAY + "Oops! Something broke! Please try again!");
    15. return;
    16. }
    17. a.getPlayers().remove(p.getName());
    18. p.teleport(locs.get(p.getName()));
    19. locs.remove(p.getName());
    20. players.remove(p.getName()); //removes player from HashMap
    21. }
    22.  


    This will return a ConcurrentModifcationException. How should I be doing this so it does not return one?
     
  2. Offline

    Forseth11

    Code:java
    1. for(Map.Entry<String, Integer> entry : players.entrySet()) {
    2. if(entry.getValue().equals(arena)) {
    3. Player p = Bukkit.getPlayer(entry.getKey());
    4. sbMan.updateScoreboard(p.getName(), 0); //removes the scoreboard
    5. removePlayer(p); //removes the player from the game
    6. }
    7. }

    You are calling the removePlayer which is in turn gets the players and removes one WHILE you are looping through the players.
    You can not remove or add items to an array/hashmap while you are looping through it.
     
  3. Offline

    fireblast709

    Starfire1337 you cannot modify the Map (with Map functions) while looping over it. Use an Iterator instead (Iterator#remove() to remove the current element)
     
Thread Status:
Not open for further replies.

Share This Page