반응형
[Java] ConcurrentModificationException - 탐색 중인 리스트 변경
발생 오류
ConcurrentModificationException 예외 발생
문제 원인
자바에서 탐색 중인 리스트가 변경될 경우 발생하는 오류이다. 탐색 중인 리스트에 요소를 추가하여 발생한 오류이다.
iterator에 remove를 사용하여 탐색 중인 리스트 내의 요소를 삭제할 수 있다. 하지만 일반적인 iterator는 추가를 지원하지 않는다.
while (!pQ.isEmpty()) {
...
//탐색 중인 리스트
for (Iterator<int[]> iterator = edges[now].iterator(); iterator.hasNext();) {
int[] list = iterator.next();
int key = list[0];
int val = list[1];
int cost = dist + val;
if (distance[key] > cost) {
distance[key] = cost;
//탐색 중인 리스트에 추가 발생
edges[start].add(new int[] {key, cost});
pQ.add(new Pair(cost, key));
}
}
}
해결 방법
이터레이터를 리스트이터레이터로 변경한 후 탐색 중인 리스트 이터레이터에 추가하여 준다.
while (!pQ.isEmpty()) {
...
//리스트 이터레이터로 변경
for (ListIterator<int[]> iterator = edges[now].listIterator(); iterator.hasNext();) {
int[] list = iterator.next();
int key = list[0];
int val = list[1];
int cost = dist + val;
if (distance[key] > cost) {
distance[key] = cost;
//탐색 중인 리스트에 추가 작업 시 리스트 이터레이터에 추가
if (start == now)
iterator.add(new int[] {key, cost});
else edges[start].add(new int[] {key, cost});
pQ.add(new Pair(cost, key));
}
}
}
참고
https://keykat7.blogspot.com/2022/02/java-concurrentmodificationexception.html