Home > Enterprise >  Iterating through collections to add items but throwing ConcurrentModificationException
Iterating through collections to add items but throwing ConcurrentModificationException

Time:11-09

package com.ripal;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Iterator;

public class Outputs {

    public void show() {
        final ArrayList<String> list = new ArrayList<String>();

        list.add("banana");
        list.add("apple");

        Iterator<String> itr = list.iterator();

        Collections.sort(list);
        while (itr.hasNext()) {
            System.out.println(itr.next()   " ");
        }
    }
}

class Test {

    public static void main(String[] args) {
        Outputs outputs = new Outputs();
        outputs.show();
    }
}

CodePudding user response:

ArrayList has a fail fast iterator. You can modify the collection only via the iterator. Any other modification done outside is detected sooner after calling the iterator methods and a ConcurrentModificationException is thrown. In your case after creating the iterator you sort the array in place and that sorting routine modifies the contents of the array, leading to ConcurrentModificationException upon using the iterator. To fix the issue, just perform the sorting before you create the iterator. Here's how it looks.

Collections.sort(list);
Iterator<String> itr = list.iterator();
  • Related