In the first line of the loop I get the error, but I don't see why. From what I read this should happen only if I'm iterating over a collection and trying to modify it at the same time, but this is not the case.
In the code, list
is of type ArrayList<Product>
.
void mergeSort() {
mergeSort(0, list.size() - 1); //128
}
private void mergeSort(int p, int r) {
if (p < r) {
int q = (p + r) / 2;
mergeSort(p, q); //133
mergeSort(q + 1, r);
merge(p, q, r); //135
}
}
private void merge(int p, int q, int r) {
List<Product> left = list.subList(p, q);
left.add(Product.PLUS_INFINITE);
List<Product> right = list.subList(q + 1, r);
right.add(Product.PLUS_INFINITE);
int i = 0;
int j = 0;
for (int k = p; k <= r; ++p) {
Product x = left.get(i).compareTo(right.get(j)) <= 0 ? left.get(i++) : right.get(j++); //147
list.set(k, x);
}
}
This is the stacktrace:
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1415)
at java.base/java.util.ArrayList$SubList.get(ArrayList.java:1150)
at ProductList$ProductSort.merge(MainClass.java:147)
at ProductList$ProductSort.mergeSort(MainClass.java:135)
at ProductList$ProductSort.mergeSort(MainClass.java:133)
at ProductList$ProductSort.mergeSort(MainClass.java:128)
at ProductList.sort(MainClass.java:95)
at MainClass.main(MainClass.java:187)