Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

자바의 반복자 대 컬렉션

<시간/>

반복자

요소가 필요할 때 요소를 검색하기 위해 컬렉션 프레임워크에서 사용됩니다.

public interface Iterator

'next' 기능과 함께 사용하여 다음 요소를 이동하고 액세스할 수 있습니다. '제거' 기능을 사용하여 데이터 구조에서 요소를 제거할 수 있습니다.

Iterator와 관련된 작업의 수가 적기 때문에 Collection에 비해 빠릅니다.

다음은 목록으로 작업하는 반복자의 예입니다 -

mport 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라는 클래스에는 주요 기능이 포함되어 있습니다. 여기에서 새로운 배열 목록이 정의되고 'add' 함수를 사용하여 요소가 추가됩니다. 반복자가 정의되고 배열 목록에 대해 반복되고 요소가 하나씩 반복된 다음 콘솔에 인쇄됩니다.

컬렉션

public interface Collection<E> extends Iterable<E>

여기서 E는 반환될 요소의 유형을 나타냅니다. 컬렉션 프레임워크는 개체 그룹을 단일 엔터티로 나타내는 데 사용할 다양한 클래스와 인터페이스를 정의하는 데 사용됩니다.

컬렉션은 '추가' 기능, '반복' 기능, '제거' 기능 및 '지우기' 기능을 사용하여 각각 요소를 추가하거나 요소를 하나씩 반복하거나 요소를 제거하거나 전체 구조를 지울 수 있습니다.

예를 들어 보겠습니다 -

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라는 클래스에는 주요 기능이 포함되어 있습니다. 여기에서 새로운 정수 배열이 정의되고 요소가 추가됩니다. 이제 새로운 Vector와 Hashtable이 정의됩니다. 요소는 'addElement' 함수를 사용하여 벡터에 추가됩니다. 요소는 'put' 기능을 사용하여 Hashtable에 추가됩니다. 세 구조 모두의 요소가 콘솔에 인쇄됩니다.