Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating through collections to add items but throwing ConcurrentModificationException

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();
    }
}

>Solution :

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Collections.sort(list);
Iterator<String> itr = list.iterator();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading