Anyone know why my hashmap manager is throwing this error

Discussion in 'Plugin Development' started by Scullyking, Jul 15, 2014.

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

    Scullyking

    Here is a simple class controlling the addition, removal and displaying of a hashmap.
    The hashmap holds ore blocks.

    addOre is called when an ore is placed.
    removeOre is called when an ore is removed.
    printOres is called when an ore is placed and removed.

    Code:java
    1. public class OreManager {
    2.  
    3. public static HashMap<String, String> ores = new HashMap<String, String>();
    4.  
    5. public static void addOre(Location location, Material material){
    6. String loc = location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ();
    7. ores.put(loc, material.name());
    8. }
    9.  
    10. public static void removeOre(Location location, Material material){
    11. String loc = location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ();
    12. for (String key : ores.keySet()){
    13. if (key.equals(loc)){
    14. ores.remove(key);
    15. }
    16. }
    17. }
    18.  
    19. public static void printOres(Player player){
    20. for (String key : ores.keySet()){
    21. player.sendMessage(key + " --- " + ores.get(key));
    22. }
    23. }
    24.  
    25. }


    Stack trace error: java.util.ConcurrentModificationException

    Visually its a weird error. Placing ores always works. It's removing them that throws this error.
    It seems to work when theres 1 or 2 ores in the hashmap, but any more throws this error.

    Thanks
     
  2. Offline

    CorrieKay

    Concurrent modification exceptions happen when you're iterating over, and modifying the contents of, a collection or iterator at the same time.the for loop at 12 is iterating over the key set, and removing the ores a the same time.
     
    Scullyking likes this.
  3. Offline

    AoH_Ruthless

    Scullyking
    You are removing keys from your hashmap while looping through it. Make a clone of the hashmap, remove keys from that, and set the original hashmap equal to the new cloned map.

    Also, look into removing all your static identifiers as a side note.

    Edit: Did not see your second post CorrieKay , ninja'd :(
     
  4. Offline

    Scullyking

  5. Offline

    NoChanceSD

    Or just use an Iterator...
     
Thread Status:
Not open for further replies.

Share This Page