에러

1. 자주 보는 에러

Warning

순회하면서 직접 삭제하면 자주 터진다.

에러원인
UnsupportedOperationExceptionArrays.asList()로 만든 고정 크기 리스트에서 add/remove 시도
ConcurrentModificationExceptionfor-each 순회 중 list.remove(), set.remove(), map.remove() 직접 호출

Arrays.asList()는 값 변경은 가능하지만 크기 변경은 불가능하다.

List<Integer> list = Arrays.asList(1, 2, 3);
 
list.set(0, 10); // 가능
// list.add(4);  // 불가능
// list.remove(0); // 불가능

가변 리스트가 필요하면 이렇게 만든다.

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

2. 순회 중 삭제

Info

순회하면서 삭제해야 하면 Iterator.remove()를 사용한다.

Iterator<Integer> it = list.iterator();
 
while (it.hasNext()) {
    int x = it.next();
 
    if (x % 2 == 0) {
        it.remove();
    }
}

또는 새 리스트를 만들어 담는 방식이 더 안전할 때가 많다.

List<Integer> result = new ArrayList<>();
 
for (int x : list) {
    if (x % 2 == 1) {
        result.add(x);
    }
}