0

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;
}
  • 1
    What does Main.append do? – twinklehawk Dec 12 '17 at 16:04
  • Possible duplicate of [ConcurrentModificationException for ArrayList](https://stackoverflow.com/questions/3184883/concurrentmodificationexception-for-arraylist) – Vel Dec 12 '17 at 16:04
  • @twinklehawk just appends another list to data list. –  Dec 12 '17 at 16:09
  • can you post the stack trace? this method is really strange. why do you iterate over the polynomial length but only operate using the data_iterator? – dev_feed Dec 12 '17 at 16:15
  • Maybe getting the iterator after calling `Main.append` – Héctor Dec 12 '17 at 16:15
  • Yeup! The answer by @twinklehawk worked. I was modifying the list in the append method. Thanks all. –  Dec 12 '17 at 16:20

2 Answers2

2

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.

Praveen
  • 1,791
  • 3
  • 20
  • 33
twinklehawk
  • 628
  • 5
  • 12
0

Iterator is created to traverse a collection and once it is created, it checks for modification every time it is used and in case of modification it throws ConcurrentModificationException when it tries to access the collection again. And as twinklehawk said, you need to create the iterator after you are done appending..

Kenny Omega
  • 398
  • 2
  • 12