Reputation:
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;
}
Upvotes: 0
Views: 94
Reputation: 398
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..
Upvotes: 0
Reputation: 639
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.
Upvotes: 2