3

Here is my code. I have an arraylist of visited elements. So I want delete these visited elements from the hashmap and below is code. It gives me concurrentmodification exception.

private static void removeVisitedNodes(ArrayList<String> arrayList) {
    // TODO Auto-generated method stub

    Iterator<String> it = arrayList.iterator();
    String temp;
    while(it.hasNext())
    {
        temp = it.next();
        System.out.println("temp is " + temp);
        Iterator<Entry<String, ArrayList<String>>> iter = neighbours_reachability_map.entrySet().iterator();

        // iterate through the hashmap to remove elements
        while (iter.hasNext()) {
            Entry<String, ArrayList<String>> entry = iter.next();
            if(entry.getValue().contains(temp)){
                //System.out.println("Contains it"  + entry.getValue().toString());
                entry.getValue().remove(temp);
            }
        }

    }
}

I checked up a few other similar questions but they did not help much. Is there a neater way to do this without causing an exception? Thanks in advance for your help.

dkatzel
  • 31,188
  • 3
  • 63
  • 67
maddie
  • 629
  • 10
  • 29
  • Works for me can you show us your input values and a stacktrace? – dkatzel Dec 06 '15 at 04:16
  • My neighbours_reachability_mapKey is - Key : 1 - [4, 5, 6] Key : 2 - [5, 6, 4] Key : 3 - [7, 4].. And the list is [4,5] So I am trying to remove all the 4s and 5s from the hashmap. The error is - Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) at acn.project.testAppend.removeVisitedNodes(testAppend.java:79) at acn.project.testAppend.main(testAppend.java:59) – maddie Dec 06 '15 at 05:22

2 Answers2

2

you can put the elementos you want to delete in another collection object and then, after finished the iteration, delete those elements

Tupac
  • 647
  • 12
  • 37
2

To remove a element whilst in the middle of iterating, use Iterator.remove().

randers
  • 5,031
  • 5
  • 37
  • 64