Collection, Map 등에서 remove 를 할 때 발생하는 ConcurrentModificationException Programmer's notes

Map 이나 Collection 에서 remove 를 할 때 java.util.ConcurrentModificationException 이 발생하는 경우가 있다.
이는 아마도 Map 이나 Collection 에서 Iterator 를 가져와서 삭제할 대상을 찾은 후 원래 Map 이나 Collection 의 인스턴스에서 해당 항목을 삭제하려 할 때 발생하는 경우일 것이다.

이와 같은 코딩을 할 때에는 Iterator.remove() 를 사용하는 것이 바람직하지만...
정작 Iterator.remove() 에는 다음과 같은 설명이 붙어있다.

remove()
          Removes from the underlying collection the last element returned by the iterator (optional operation).
optional...
구현했다고 확신하면 이것을 써야 한다?

Collection 을 ArrayList 나 HashMap 등의 명시적인 구현체를 타입으로 쓸 때야 구현여부를 확인하고 사용하면 되겠지만,
권장하는 방법은 그냥 Map 이나 List 등의 인터페이스로 선언해서 쓰라는 것이 아니던가?

Iterator.remove() 를 쓰고 싶었지만 iteration 으로 사용할 인스턴스를 새로 만들어서 그것으로 iteration 작업을 하고 remove() 는 원래 Collection 오브젝트로 해야겠다.

Iterator tarKeyIter = new HashSet(target.keySet()).iterator();
while (tarKeyIter.hasNext()) {
    Object key = (Object)tarKeyIter.next();
    if(!source.containsKey(key)) {
        target.remove(key);
        log.debug("remove : "+key);
    }
}


트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://sayjava.egloos.com/tb/2990121 [도움말]

덧글

덧글 입력 영역