ConcurrentModificationException
linkedList를 이용하여 다음 코드와 같이 문제를 풀어보려고 했는데 ConcurrentModificationException이 발생했다.
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<>();
Iterator<Integer> it = linkedList.iterator();
for (int i = 1; i <= 10; i++) {
linkedList.add(i);
}
System.out.println(it.hasNext());
System.out.println(it.next());
}
Exception in thread "main" java.util.ConcurrentModificationException
Iterator가 대충 Collection의 원소들을 하나하나 읽어오는 방법 정도라는 것 밖에 몰랐기 때문에 뭐 때문에 예외가 발생한 것인지 잘 모르겠어서 구글링을 해 보았다. 밑의 두 블로그를 참고하였다.
Iterator의 인터페이스 구조와 ConcurrentModification 예외가 또 언제 발생할 수 있는지에 대해 자세히 설명이 되어 있었다. Iterator의 구조까지는 잘 모르겠으나, 일단은 내가 틀린 이유는 간결했다. 처음에 Iterator을 만들고 나서 Iterator가 참조하는 컬렉션의 자료가 바뀌었기 때문이었다. Iterator는 사용하는 바로 그 때 선언을 해주어야 한다는 것을 알게 되었다.
코드 수정
따라서 아래의 코드처럼 Iterator의 선언을 add가 다 된 시점에서 해주어 해결하였다.
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<>();
for (int i = 1; i <= 10; i++) {
linkedList.add(i);
}
Iterator<Integer> it = linkedList.iterator();
System.out.println(it.hasNext());
System.out.println(it.next());
}
true
1
'STUDY > JAVA' 카테고리의 다른 글
[TIL] 프로그래머스 lv.2 다음 큰 숫자 (비트연산자) (0) | 2023.06.22 |
---|---|
[TIL] 예외 되던지기(Exception re-throwing)는 언제 사용될까? (0) | 2023.06.21 |
[TIL] < 자바의 정석 > 예제 HighLow - 예외처리해보기 (0) | 2023.06.15 |
[TIL] printStackTrace()는 왜 아래에 찍힐까? (0) | 2023.06.14 |
[TIL] Getter와 Setter. 왜 쓸까? (1) | 2023.06.12 |