공부/프로그래밍 오류

[Java] ConcurrentModificationException - 탐색 중인 리스트 변경

감자 바보 2022. 8. 11. 19:37
반응형

[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

 

[JAVA] ConcurrentModificationException와 iterator : 탐색 도중 리스트가 변경되는 경우

알고리즘, 코딩 테스트, C++, java, 파이썬, AI, 백준, 기업 코딩 테스트, 자료구조, 프로젝트, codeforces, unity, android

keykat7.blogspot.com