일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- @IdClass
- Error creating bean with name
- ERD 작성
- REST API 규칙
- 최종 프로젝트
- Q 클래스
- Filter
- Unsatisfied dependency
- REST란
- 1차캐시
- 스프링 부트 공식 문서
- 인텔리제이
- 스프링 부트 기능
- JoinColumn
- git
- github
- uncheck Exception
- JPA주의사항
- jpa회원가입
- json gson 차이
- JPA
- 스프링부트오류
- jwt메서드
- json
- 복합키
- 빈생성안됨
- Spring Spring boot 차이
- queryDSL
- spring서버
- jpa에러
- Today
- Total
Everyday Dev System
0602_TIL : ConcurrentModificationException 본문
0602_TIL : ConcurrentModificationException
chaeyoung- 2023. 6. 2. 19:28
# 문제점 :
List 타입의 객체에서 요소를 순회하는 중에 요소를 삭제한 후에 index가 변경되어 일부 요소는 순회가 안됐다.
아래와 같은 오류가 발생했다.
List<Food> saleFoods 변수 내에서 특정 조건에 맞을 경우,
saleFoods 내에서 sf라는 객체의 요소를 삭제하는 코드 부분이다.
for (Food sf : saleFoods) {
if(resultCnt == 0){
saleFoods.remove(sf);
}
}
# 시도 :
saleFoods.remove(sf);
saleFoods.add(new Food("",0.0,"",0));
삭제를 하고, 빈 객체를 생성해보았지만, salesFoods를 순회하며 출력할 때,
아래와 같이 출력이 되어, 출력이 되지 않도록 해야 하므로 이 방법은 옳지 않다.
Result :
| W 0.0 | 0개 |
saleFoods.remove(sf);
saleFoods.add(null);
null을 추가하면 순회할 때 null이 아닐 경우에 출력하도록 하면 된다.
그러나, ConcurrentModificationException 해당 오류는 반복되었다.
# 해결 방법 :
List 객체 타입의 변수를 만들어서 해당 List에 삭제할 객체를 추가한 후,
삭제해야 할 원본 saleFoods에서 removed를 saleFoods.removeAll(removed); 를 수행하였다.
private void deleteSaleFoods(List<Food> saleFoods) {
List<Food> removed = new ArrayList<>();
for (Food sf : saleFoods) {
if (resultCnt == 0) {
removed.add(sf);
} else { // if() of the end
// nothing logic
} // if-else() of the end
} // for() of the end
saleFoods.removeAll(removed);
}
참조 : https://codechacha.com/ko/java-concurrentmodificationexception/
Java - ConcurrentModificationException 원인 및 해결 방법
ConcurrentModificationException는 보통 리스트나 Map 등, Iterable 객체를 순회하면서 요소를 삭제하거나 변경을 할 때 발생합니다. removeIf, removeAll, Iterable 등의 메소드를 이용하여 리스트 순회 중 요소를
codechacha.com
'내배캠 주요 학습 > TIL : Today I Learned' 카테고리의 다른 글
0607_TIL : ClassNotFoundException 해결 (0) | 2023.06.07 |
---|---|
TIL_0605 : GitHub resolve conflicts 비활성화 (0) | 2023.06.05 |
0601_TIL : Stream forEach() 활용 (1) | 2023.06.01 |
0531_TIL : 자바 코드 가독성 향상법, 객체 지향 코드 작성법 (0) | 2023.06.01 |
0531_TIL : 배열과 List의 차이 (0) | 2023.05.31 |