Everyday Dev System

0602_TIL : ConcurrentModificationException 본문

내배캠 주요 학습/TIL : Today I Learned

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