Search code examples
javaarraylistconcurrentmodification

java.util.ConcurrentModificationException occurs in the program


I am trying to copy a limited number of elements from List<Integer> data being passed from the main method, into another List<Integer> remainder. When I debug the program and run the code lines step by step, there's no error. But when I try to run the code normally I get the ConcurrentModificationError. I've looked upon other SO threads and I was unable to solve it.

public static List<Integer> calculate_remainder(List<Integer> data, int[] polynomial, List<Integer> append)
{
    List<Integer> remainder = new ArrayList<>();
    List<Integer> temp = new ArrayList<>();
    Iterator<Integer> data_iterator = data.iterator();

    data = Main.append(data, append);

    for (int i = 0; i < polynomial.length; i++)
    {
        if (data_iterator.hasNext())
        {
            remainder.add(data_iterator.next());
        }
    }

Update 1:

public static List<Integer> append(List<Integer> data, List<Integer> append)
{
    data.addAll(append);
    return data;
}

Solution

  • Iterator throws ConcurrentModificationException when the underlying list has been changed after the Iterator is created (search for fail-fast in ArrayList JavaDoc).

    Try moving the creation of the Iterator to after the Main.append call.