<aside> ☑️ 참고 블로그

  1. Iterable과 Collection의 관계

  2. Collection의 상속관계

  3. Iterator 사용 방법

</aside>

출처: Collection의 상속관계

출처: Collection의 상속관계

상속관계를 보면 , Collection (Interface)는 Iterable (Interface)를 상속받고 있다.

→ 아래 Eclipse에서 직접 가져온 Interface들이다. Iterable<T>를 보면 abstrac method로 iterator()를 만들어 놓았다. (참고 - 추상 메소드)

→ Collection이 Iterable interface를 상속받았으니 iterator() 추상 method 또한 상속받았을 것이고, 다음과 같이 Collection interface에 추가되어 있는 것을 확인할수 있을 것이다.

public interface Iterable<T> {
    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    Iterator<T> iterator();

    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

    default Spliterator<T> spliterator() {
        return Spliterators.spliteratorUnknownSize(iterator(), 0);
    }
}
public interface Collection<E> extends Iterable<E> {
    // Query Operations

    int size();

    boolean isEmpty();

    boolean contains(Object o);

    /**
     * Returns an iterator over the elements in this collection.  There are no
     * guarantees concerning the order in which the elements are returned
     * (unless this collection is an instance of some class that provides a
     * guarantee).
     *
     * @return an {@code Iterator} over the elements in this collection
     */
    Iterator<E> iterator();

		//...
}

위의 Collection 까지의 Interface들을 그 아래 List, Queue, Set Interface가 상속받고 이후 ArrayList, LinkedList 등이 위의 Interface를 구현하면서 iterator() 등을 각자 자료구조에 맞게 구현한 것.

Iterable의 역할 - iterator()메소드를 하위 클래스에서 무조건 구현을 하게 만들기 위함이다.