java.util.Iterator

서버란·2024년 8월 31일

자바 궁금증

목록 보기
11/35

Iterator는 자바의 컬렉션(Collection)에 저장된 요소들을 하나씩 순차적으로 접근하기 위한 인터페이스입니다. 컬렉션에 저장된 데이터를 읽는 방법을 표준화하기 위해 Iterator 인터페이스가 제공되며, 이 인터페이스는 컬렉션에서 요소를 순차적으로 접근하고, 필요시 요소를 제거하는 기능을 제공합니다.

Iterator 인터페이스의 정의

  • Iterator 인터페이스는 주로 컬렉션의 요소들을 반복하여 처리할 때 사용됩니다. 이 인터페이스는 세 가지 주요 메서드를 가지고 있습니다:

  • boolean hasNext(): 다음 요소가 있는지 확인하여, 있으면 true, 없으면 false를 반환합니다.

  • Object next(): 다음 요소를 반환합니다.

  • void remove(): 현재 위치의 요소를 컬렉션에서 제거합니다.

Iterator 인터페이스 예시:

public interface Iterator {
    boolean hasNext();   // 다음 요소가 있는지 확인
    Object next();       // 다음 요소 반환
    void remove();       // 현재 요소 제거
}

Collection 인터페이스와 iterator() 메서드

  • Collection 인터페이스는 자바의 모든 컬렉션 클래스에서 기본적으로 구현해야 하는 인터페이스입니다. Collection 인터페이스에는 컬렉션에 저장된 요소들에 대해 Iterator 객체를 반환하는 iterator() 메서드가 정의되어 있습니다.

  • 이 메서드는 컬렉션 클래스에 저장된 요소들을 순차적으로 탐색할 수 있는 Iterator 객체를 반환하며, List와 Set과 같은 자식 인터페이스도 이 메서드를 상속받습니다.

Collection 인터페이스 예시:

public interface Collection {
    ...
    public Iterator iterator();   // Iterator 반환
    ...
}

사용예시

  • Student 클래스
public class Student {

    int no;
    String name;

    public Student(int no, String name) {
        this.no = no;
        this.name = name;
    }

    public int getNo() {
        return no;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return this.no + ": " + this.name;
    }

}
  • Group 클래스
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Group<E extends Student> implements Iterable<E>{
    List<E> list;
    int index =0;

    public Group(){
        list = new ArrayList<>();
    }

    public void addPerson(E student){
        list.add(student);
        index++;
    }
    public int size() {
        return index;
    }

    public E getE(int index){
        return list.get(index);
    }

    public int getIndex(){
        return this.index;
    }

    @Override
    public Iterator<E> iterator() {
        return this.list.iterator();
    }

    public void sort(){
        Collections.sort(this.list, new StudentNoComparator());
    }
}
  • Main 클래스
  import java.util.Iterator;

public class Main {

    public static void main(String[] args) {
        Group<Student> group = new Group<>();

        group.addPerson(new Student(3, "Com"));
        group.addPerson(new Student(4, "Elice"));
        group.addPerson(new Student(5, "David"));
        group.addPerson(new Student(1, "Bob"));
        group.addPerson(new Student(2, "Ace"));

        for (Student student : group) {
            System.out.println(student);
        }
        group.sort();

        for (Student student : group) {
            System.out.println(student);
        }

        group.list.forEach(System.out::println);

        
    }
}

group에서 hasNext하고 next를 구현안해도 되나?

  • 예, Group 클래스에서 hasNext()와 next() 메서드를 구현하지 않아도 괜찮습니다. 그 이유는 Group 클래스가 Iterable 인터페이스를 구현하고 있으며, iterator() 메서드에서 list.iterator()를 반환하고 있기 때문입니다.

  • 이유:
    iterator()의 반환 값: iterator() 메서드에서 ArrayList의 Iterator를 반환하고 있습니다. ArrayList는 자바 표준 라이브러리에서 제공하는 컬렉션이므로, 이 컬렉션에 대한 Iterator는 이미 hasNext()와 next() 메서드를 포함하고 있습니다.

  • 내부 구현: ArrayList의 Iterator는 hasNext()와 next()를 구현하고 있으므로, Group 클래스가 별도로 hasNext()와 next()를 구현할 필요가 없습니다.

따라서 Group 클래스에서는 iterator() 메서드를 통해 ArrayList의 Iterator를 반환하고 있기 때문에, hasNext()와 next()를 직접 구현할 필요가 없습니다.

  • 예시:
public class Main {
    public static void main(String[] args) {
        Group<Student> group = new Group<>();
        group.addPerson(new Student(1, "Alice"));
        group.addPerson(new Student(2, "Bob"));

        // Using the iterator
        Iterator<Student> iterator = group.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().getName());
        }
    }
}

위 코드에서 iterator.hasNext()와 iterator.next()는 ArrayList의 Iterator를 사용하여 작동하게 됩니다.

profile
백엔드에서 서버엔지니어가 된 사람

0개의 댓글