728x90
반응형

ArrayList.remove()를 통해 List 특정항목을 제거해야 했다.

 

작성한 코드는 아래와 같았다.

1
2
3
4
5
6
7
8
9
10
11
List<Integer> delIndexList = new ArrayList<>();
/** 조건에 의해 삭제할 index를 delIndexList에 추가 **/
 
if (delIndexList != null && delIndexList.size() > 0) {
    // List에서 remove시 남은 요소들의 index가 변경되므로 2개 이상의 삭제시 문제 방지를 위해 
    // 삭제할 index를 가진 delIndexList를 역정렬하여 진행
    delIndexList = delIndexList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    for (Integer index : delIndexList) {
        list.remove(index);
    }
}
cs

 

그러나 이상하게도 9번 라인에서 삭제가 되지 않는 것이다.

임의로 1을 넣어 진행해보니 문제가 없었다.

즉, ArrayList.remove(index)에서 index는 int 형으로 해야한다.

 

아쉽게도 integer를 사용해도 별 다른 에러는 나오지 않고 넘어가고 삭제되지 않아 처음에는 쉽게 원인을 인지하기 어렵다.

 

 

 

* 관련글

[java] ArrayList를 다룰때 흔한 실수 : https://deonggi.tistory.com/65

 

728x90
반응형

+ Recent posts