Back-End/Spring Boot
Spring Boot | Java ConcurrentModificationException (순회 도중 삭제하기)
개발자티포
2023. 8. 22. 17:22
728x90
반응형
순회를 하는 도중에 무언가 작업을 한다면 ConcurrentModificationException 이 뜰 수 있다.
다음과 같이 써보자.
List<String> list = new ArrayList<>();
list.add("str1");
list.add("str2");
list.add("str3");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
if ("str1".equals(str)) {
iterator.remove();
}
}
아래와 같이 removeIf 메소드로 간편하게 사용할 수도 있다.
list.removeIf(event -> !otherList.contains(event));
728x90
반응형