0

Pls help me with this problem. I have Graph represent by Structure HashMap> graf; and i need to go throught that hashmap and set and remove some edges. How can i do that ? code give me this exception

Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$KeyIterator.next(Unknown Source)


      public String vratCestu() {
            String vrat = "";
            for(String s: this.graf.keySet()){
                if (this.graf.get(s).size() != 0)

                    for(String k : this.graf.get(s)){
                            this.graf.get(s).remove(k);
                            this.graf.get(k).remove(s);
                            vrat += k + "; ";

                    }
                }
                return vrat;
            }
  • 1
    possible duplicate of [ConcurrentModificationException and a HashMap](http://stackoverflow.com/questions/602636/concurrentmodificationexception-and-a-hashmap) – Peter Lawrey Apr 23 '14 at 13:40

2 Answers2

1

Instead of enhanced for loop for(String s: this.graf.keySet()), use an Iterator You cannot modify the collection while iterating over it with the use of enhanced for loop.

Mubin
  • 4,192
  • 3
  • 26
  • 45
0

You cannot modify your HashSet directly while iterating over.

Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129