2

How do I resolve ConcurrentModificationException 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);

    }

}
Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
themaster
  • 453
  • 11
  • 32
  • 1
    No, it's because you are modifying the array concurrently. Use a vector or a synchronized arraylist instead. – Ioan Jul 16 '16 at 18:45
  • See [this](http://stackoverflow.com/questions/18448671/how-to-avoid-concurrentmodificationexception-while-removing-elements-from-arr) possible duplicate "Can't archive with enhanced for loop" – Malatesh Jul 16 '16 at 18:53

1 Answers1

4

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).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523