Iterator
Dùng trong Collection Framework để truy xuất phần tử khi cần.
public interface Iterator
Có thể dùng với hàm next để di chuyển và truy cập phần tử tiếp theo. Hàm remove dùng để xóa phần tử khỏi cấu trúc dữ liệu.
Nhanh hơn so với Collections, vì số phép toán liên quan đến Iterator ít hơn.
Dưới đây là ví dụ Iterator làm việc với List:
Ví dụ
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("List chứa các phần tử sau: ");
while (iterator.hasNext())
System.out.print(iterator.next() + ",");
System.out.println();
}
}
Kết quả
List chứa các phần tử sau: Its,a,sample,
Lớp Demo chứa main. ArrayList mới định nghĩa, phần tử thêm bằng add. Iterator định nghĩa và duyệt ArrayList, phần tử lặp từng cái một và in ra console.
Collection
public interface Collection<E> extends Iterable<E>
Ở đây, E tham chiếu đến kiểu phần tử trả về. Collection Framework dùng để định nghĩa các lớp và interface khác nhau sẽ dùng để biểu diễn nhóm đối tượng như một thực thể duy nhất.
Collection dùng add, iterate, remove, clear để thêm phần tử, duyệt từng cái, xóa phần tử hoặc xóa toàn bộ cấu trúc.
Hãy xem ví dụ:
Ví dụ
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("Phần tử đầu trong mảng: ");
System.out.println(my_arr[0]);
System.out.print("Phần tử đầu trong vector: ");
System.out.println(my_vect.elementAt(0));
System.out.print("Phần tử đầu trong hashtable: ");
System.out.println(my_hashtab.get(0));
}
}
Kết quả
Phần tử đầu trong mảng: 56 Phần tử đầu trong vector: 0 Phần tử đầu trong hashtable: sample
Lớp Demo chứa main. Mảng nguyên mới định nghĩa, phần tử thêm. Vector mới và Hashtable định nghĩa. Phần tử thêm vào Vector bằng addElement. Phần tử thêm vào Hashtable bằng put. Phần tử của cả ba cấu trúc in ra console.