Wednesday, September 28, 2011

Oh! MY java.util.ConcurrentModificationException


 It's one of the common exception that occurs when you iterate over a collection and try to remove an entry.

Few examples are:
List<String> list = new ArrayList<String>();
list.add("2);
list.add("3");
list.add("4");
for(String s: list){
   if(s.equals("2")){
      list.remove(s);
   }

} and run the snippet, we can see  Exception in thread "main" java.util.ConcurrentModificationException.

Now just a little modification, we will use Iterator, since it can allow to remove the element while iterating, so the resultant code looks like

 List<String> list = new ArrayList<String>();
 for(Iterator<String> it=list.iterator;it.hasNext();){
    if(it.next().equals("2"){
     it.remove();
}
}

System.out.println("Size of List"+list.size());
Which will give output as 2 :)

-----------------------------------------------------
Now the same for HashMap

Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("122", 233);
        map.put("124", 456);
        map.put("125", 345);
        for (Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "    " + entry.getValue());
        }
        for (Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getKey().equals("125")) {
                map.remove(entry.getKey());
            }
        }
Same exception,
Now modify the loop as
for(Iterator<Entry<String, Integer>> iterator= map.entrySet().iterator();iterator.hasNext();){
            Entry<String, Integer> next = iterator.next();
            if(next.getValue()==456){
                iterator.remove();
            }
        } Its Gone!













No comments:

Post a Comment