Spring, Apache, Java

Collection Vs. Iterator

cwchoiit 2023. 10. 4. 08:52
728x90
반응형
SMALL
728x90
반응형
SMALL

Iterator, Collection 모두 자주, 용이하게 사용되고 있지만 쓰임새는 상당히 다른데 차이점을 모른 채 사용했던 내가 Collection으로 loop를 돌리면서 문제를 발견하고 그 문제를 공부하면서 알게 된 내용을 작성해보고자 한다.

 

참고 자료 https://www.geeksforgeeks.org/iterator-vs-collection-in-java/

 

Iterator vs Collection in Java - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

Iterator

- Declaration

public interface Iterator

Type Parameter:
E - the type of elements returned by this iterator

Iterator는 각 요소를 회수하기 위해 Java의 Collection framework에서 사용된다.

사용 가능한 Method로는 forEachRemaining, hasNext, next, remove가 있다.

 

Collection

- Declaration

public interface Collection<E> extends Iterable<E>

Type Parameter:
E - the type of elements returned by this iterator

Collection은 하나의 단위로 표현된 각각의 객체의 그룹이다.

사용 가능한 Method로는 add, addAll, clear, contains 등 상당수가 있다. 

 

 

Iterator Vs. Collection

- Iterator는 next() 또는 remove()를 통해서만 요소 간 변화를 줄 수 있지만, Collection은 add(), iterate, remove(), clear()와 같은 메서드를 사용할 수 있다.

- Iterator는 Collection보다 더 속도가 빠르다. 왜냐하면 Iterator Interface가 더 적은 수의 Operation을 가지고 있기 때문

- Collection을 사용해서 Loop operation을 수행할 때 Collection의 수정, 삭제는 불가능하다. 더 정확한 표현으로는 ConcurrentModificationException이 발생할 수 있다. 즉, 이 데이터를 어디선가 사용하는 중에 다른 어떤곳에서 이 데이터를 삭제 또는 수정하는 경우 데이터 불일치 현상이 발생할 수 있다. 

 

ConcurrentModificationException을 해결하고자 Iterator를 사용한다. 예를 들면 loop operation안에서 특정 원소를 삭제하는 경우 다음과 같은 코드를 작성할 수 있다.

Iterator<Link> iterator = autoSyncQueue.iterator();
while (iterator.hasNext()) {
    Link li = iterator.next();
    // Perform actions on 'li'
    if (condition) {
        iterator.remove(); // Safely remove the current element
    }
}

 

 

728x90
반응형
LIST