Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바(Java) Iterator와 Collection의 차이점 완벽 정리

Iterator(반복자)란?

Iterator는 자바 컬렉션 프레임워크(Collection Framework)에서 저장된 요소들을 필요한 시점에 하나씩 순차적으로 꺼내어 접근할 수 있도록 지원하는 인터페이스입니다.

public interface Iterator

Iterator는 next() 메서드를 통해 커서를 다음 요소로 이동시키며 각 요소에 접근하고, remove() 메서드를 사용해 현재 위치의 요소를 데이터 구조에서 안전하게 삭제할 수 있습니다.

또한 Iterator는 내부적으로 처리해야 하는 연산의 수가 적기 때문에, 컬렉션 객체를 직접 순회하는 방식에 비해 일반적으로 더 빠른 성능을 보여줍니다.

Iterator 예제 코드

다음은 리스트(List)에서 Iterator를 사용하는 예제입니다.

import java.io.*;
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        ArrayList<String> my_list = new ArrayList<String>();
        my_list.add("Its");
        my_list.add("a");
        my_list.add("sample");

        Iterator iterator = my_list.iterator();
        System.out.println("The list contains the following elements : ");
        while (iterator.hasNext())
            System.out.print(iterator.next() + ",");
        System.out.println();
    }
}

실행 결과

The list contains the following elements :
Its,a,sample,

위 코드에서 Demo 클래스의 main 함수 안에서 새로운 ArrayList가 생성되고, add() 메서드를 통해 문자열 요소들이 추가됩니다. 이후 iterator() 메서드로 반복자를 얻어 hasNext() 조건문과 함께 리스트의 모든 요소를 하나씩 순회하며 콘솔에 출력합니다.

Collection(컬렉션)이란?

public interface Collection<E> extends Iterable<E>

여기서 타입 매개변수 E는 컬렉션이 담게 될 요소의 자료형을 의미합니다. 컬렉션 프레임워크는 여러 개의 객체를 하나의 단위로 묶어 관리할 수 있도록 다양한 클래스와 인터페이스를 정의해 놓은 구조입니다.

Collection 인터페이스는 add()(요소 추가), remove()(요소 삭제), clear()(전체 비우기) 등의 메서드를 제공하며, Iterable을 상속하기 때문에 iterator() 메서드를 통해 요소를 순회할 수도 있습니다.

Collection 예제 코드

아래 예제는 배열(Array), 벡터(Vector), 해시테이블(Hashtable) 세 가지 자료구조를 함께 사용하는 방법을 보여줍니다.

import java.io.*;
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        int my_arr[] = new int[] {56, 78, 90};
        Vector<Integer> my_vect = new Vector();
        Hashtable<Integer, String> my_hashtab = new Hashtable();

        my_vect.addElement(0);
        my_vect.addElement(100);
        my_hashtab.put(0, "sample");
        my_hashtab.put(100, "only");

        System.out.print("The first element in the array is ");
        System.out.println(my_arr[0]);
        System.out.print("The first element in the vector is ");
        System.out.println(my_vect.elementAt(0));
        System.out.print("The first element in the hashtable is ");
        System.out.println(my_hashtab.get(0));
    }
}

실행 결과

The first element in the array is 56
The first element in the vector is 0
The first element in the hashtable is sample

Demo 클래스의 main 함수에서는 먼저 정수형 배열을 선언하고 값을 초기화합니다. 이어서 Vector 객체를 생성해 addElement() 메서드로 요소를 추가하고, Hashtable 객체에는 put() 메서드로 키-값 쌍을 삽입합니다. 마지막으로 세 가지 자료구조의 첫 번째 요소를 각각 조회하여 콘솔에 출력합니다.

정리: Iterator vs Collection 핵심 차이

  • 역할: Collection은 데이터를 저장·관리하는 컨테이너이고, Iterator는 그 안의 요소를 순회·접근하는 도구입니다.
  • 성능: Iterator는 연산 오버헤드가 적어 단순 순회 시 더 효율적입니다.
  • 기능: Collection은 add, remove, clear 등 다양한 조작 기능을 제공하며, Iterator는 next와 remove 중심으로 동작합니다.