Skip to content

[item 58] Iterable을 직접 구현 #47

Open

Description

@IAGREEBUT

350page
Iterable을 처음부터 직접 구현하기는 까다롭지만, "원소들의 묶음을 표현하는 타입"을 작성해야 한다면 Iterable을 구현하는 쪽으로 고민해보기 바란다.
라는 구문이 있는데 혹시 예시를 들어서 설명해주실 수 있을까요?

Activity

  1. zpqmdh commented on Jul 2, 2024

    @zpqmdh
    Contributor

    for-each문은 컬렉션과 배열, Iterable 인터페이스를 구현한 객체를 동일한 관용구로 순회할 수 있습니다. 즉 직접 작성한 타입이 Iterable 인터페이스를 구현하도록 하게 하면, for-each문을 사용할 수 있습니다.

    image

    이때, Iterable 인터페이스는 iterator 메서드를 가지고 있기 때문에, 해당 인터페이스를 구현하기 위해서는 iterator 메서드를 무조건 구현해야 합니다. for-each문이 바로 이 iterator 메서드를 통해 순회하기 때문입니다.

    iterator 구현 방법에는 내부 클래스 혹은 익명 클래스를 사용하거나, 람다 표현식을 사용할 수 있습니다.

    아래의 예제는 스트림 API를 사용하여 순회한 것입니다.

    import java.util.Arrays;
    import java.util.Iterator;
    
    public class MyType<T> implements Iterable<T> {
        private T[] items;
    
        public MyType(T[] items) {
            this.items = items;
        }
    
        @Override
        public Iterator<T> iterator() {
            return Arrays.stream(items).iterator();
        }
    
        public static void main(String[] args) {
            Integer[] numbers = {1, 2, 3, 4, 5};
            MyType<Integer> myCollection = new MyType<>(numbers);
    
            for (Integer number : myCollection ) {
                System.out.println(number);
            }
        }
    }

    이렇게 Iterable 인터페이스를 구현한 타입을 만들면, 아이템 58의 내용을 적용할 수 있습니다.

  2. added
    question
    on Jul 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions