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!













Sunday, September 25, 2011

Groovy is fun!


Just played around with a few xml and Groovy( i think it has a very short learning curve, i could follow the code,even though i ve no much experience in it), its first class support to xml is brilliant .

Just
def writer = new StringWriter();
def builder = new MarkupBuilder(writer);
builder.root {
child {
title "Child 1"
}
}
println(writer);  

This is enough to build a small xml file. Parsing is also fun( have tried XmlSlurper). Since they are plain java byte codes after compilation, only an additional groovy library is enough for calling these utilities from our java application.Groovy can be handy if we want to write some fast utility classes(In fact, we can call it as Super Java). Java + Groovy DSL is fun. Now planning to compose a full fledged xml utility class with groovy.