Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Iterator vs Collection ใน Java

Iterator

ใช้ใน Collection Framework เพื่อดึงข้อมูล elements ตามที่ต้องการ

public interface Iterator

ใช้เมธอด next() เพื่อเลื่อนและเข้าถึง element ถัดไป ใช้ remove() ลบ element ออกจากโครงสร้างข้อมูล Iterator เร็วกว่า Collections เพราะมี operation น้อยกว่า

ตัวอย่าง Iterator กับ List

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

public class Demo {
    public static void main(String[] args) {
        ArrayList my_list = new ArrayList();
        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 สร้าง ArrayList เพิ่มข้อมูล สร้าง Iterator จาก list วนลูป hasNext() และ next() พิมพ์แต่ละ element

Collection

public interface Collection extends Iterable

E หมายถึงประเภทของ element ที่จะคืนค่า Collection Framework ใช้กำหนด class และ interface ต่างๆ เพื่อแทนกลุ่มของ objects เป็น entity เดียว Collection ใช้ add(), iterate(), remove(), clear() สำหรับเพิ่ม วนลูป ลบ และล้างโครงสร้างตามลำดับ

ตัวอย่าง Collection

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

public class Demo {
    public static void main(String[] args) {
        int my_arr[] = new int[] {56, 78, 90};
        Vector my_vect = new Vector();
        Hashtable 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 สร้าง array, Vector, Hashtable เพิ่มข้อมูลเข้าไป แล้วเข้าถึง element แรกของแต่ละโครงสร้าง