themaster themaster - 4 months ago 9
Java Question

Concurrent Modification Exception

How do I resolve Concurrent Modification Exception from the below program .
I need a list where first element is "Znk" ,and then the sorted listed following it .

I understand ,I am getting this because I am adding and removing in the same iteration . But how do I resolve this and get the desired output.

public class ListSwapIndex {

public static void main(String[] args) {
// TODO Auto-generated method stub

ArrayList<String> swapIndex = new ArrayList<String>();
ArrayList<String> swapIndextemp = new ArrayList<String>();
swapIndex.add("Ank");
swapIndex.add("Znk");
swapIndex.add("Bnk");
swapIndex.add("Dnk");
swapIndex.add("Enk");
swapIndex.add("Lnk");

for (String string : swapIndex) {
if(string.equals("Znk")){
swapIndextemp.add(string);
swapIndex.remove(string);
}
}
swapIndextemp.addAll(swapIndex);
System.out.println(swapIndextemp);

}

}

Answer

You are not allowed to modify a collection concurrently with iterating it. Java protects from this by checking the collection being iterated, and failing quickly when a modification is found.

Using ListIterator<T> instead of iterating with for-each loop fixes the problem, because list iterator of ArrayList allows deletions:

for (ListIterator<String> iter=swapIndex.listIterator(); iter.hasNext() ; ) {
    String current = iter.next();
    if(current.equals("Znk")){
        swapIndextemp.add(string);
        iter.remove();
    }
}

Note, however, that this approach is suboptimal, because removal from an array list is an O(n) operation, resulting in O(n2) overall performance. You would be better off iterating the list twice - once to put all "Znk"s at the front, and once more to put the rest of the items after it. This gives you an overall performance of O(n).

Comments