iterator는 반복자다. collections 의 클래스들이 공통적으로 가지고 있는 API다. 컨테이너에 담긴 값들을 하나씩 꺼내서 하나 하나 기능을 처리할 수 있도록 한다.
아래 코드를 통해 자세히 알아보자.
public class SetDemo {
public static void main(String[] args) {
HashSet<Integer> A = new HashSet<Integer>();
A.add(1);
A.add(2);
A.add(3);
Iterator hi = A.iterator();
while(hi.hasNext()) {
System.out.println(hi.next());
}
}
}
iterator는 hasNext와 next라는 메소드를 가지고 있다. 위의 코드를 실행하면 1,2,3이 차례대로 출력된다.
iterator는 Collections에 있는 모든 API에 적용되므로, Arraylist, Set 등 모든것에도 출력이 가능하다.
위 HashSet을 Arraylist 혹은 Collections로 바꿔도 똑같이 출력된다는 의미다.