[Solved] Why did I get this exception?

Discussion in 'Spigot Plugin Development' started by BryceTheCoder, May 7, 2015.

  1. #1 BryceTheCoder, May 7, 2015
    Last edited: May 12, 2015
  2. gigosaurus

    Supporter

    • Agree Agree x 2
  3. Instead of doing this :
    Code (Text):
    for (Block b : Main.this.timer.keySet()) {
                                    int newTime = ((Integer)Main.this.timer.get(b)).intValue() + 1;//TODO: Will gc pickup int?
                                    Main.this.timer.put(b, Integer.valueOf(newTime));
                                    if (newTime >= Main.this.getTime(b)) {
                                            b.setType((Material)Main.this.block.get(b));
                                            Main.this.block.remove(b);
                                            Main.this.timer.remove(b);
                                    }
                            }
    Create a "copy set" of the keySet. Then, iterate over that copy set and do basically the same code but remember to remove the object from the actual hashmap. This is because when you use an enchanced for loop, you can't modify the list while in that loop because it would cause a lot of errors just like if you're reading something and expect it to be a particular size but then someone changes it while you're reading it and suddenly you don't know what size it is anymore and you're already halfway through. If you want to do this without using a copy set, do what gigosaurus said and use the set's iterator. Then, just iterate over the elements and remove as necessary.
     
    • Optimistic Optimistic x 1
  4. gigosaurus

    Supporter

    Seriously, use an Iterator, it's what it's there for. Cloning the set to just remove from the original later on is both time consuming and a waste of resources, plus it requires more work to do so there's more room for mistakes.
     
  5. An other option is to use the same code but instead of temoving items just add the key you wish to remove to a second set. Once the for loop is complete iterate through this second set of "marked for removal keys" removing them from the map.
     
    • Optimistic Optimistic x 1