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;
}
6
  • 1
    What does Main.append do? Commented Dec 12, 2017 at 16:04
  • Possible duplicate of ConcurrentModificationException for ArrayList Commented Dec 12, 2017 at 16:04
  • @twinklehawk just appends another list to data list. Commented Dec 12, 2017 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? Commented Dec 12, 2017 at 16:15
  • Maybe getting the iterator after calling Main.append Commented Dec 12, 2017 at 16:15

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.