Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa Iterator và ListIterator trong Java

Bảng so sánh

Tiêu chíIteratorListIterator
Áp dụng choTất cả Collection (Set, List, Queue, Deque, Map)Chỉ List (ArrayList, LinkedList, Vector...)
Cách lấy instancecollection.iterator()list.listIterator() hoặc list.listIterator(index)
Duyệt dữ liệuChỉ tiến (forward) – hasNext(), next()Tiến & lùi – hasNext(), next(), hasPrevious(), previous()
Xóa phần tửremove() (hỗ trợ)remove() (hỗ trợ)
Thêm phần tửKhông hỗ trợ (ném ConcurrentModificationException)add(E e) – thêm trước con trỏ hiện tại
Sửa đổi phần tửKhông hỗ trợset(E e) – thay thế phần tử vừa truy xuất
Lấy indexKhông cónextIndex(), previousIndex()

Ví dụ minh họa

import java.util.*;

public class IteratorVsListIteratorDemo {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));

        // Iterator – chỉ tiến
        System.out.println("Iterator (forward):");
        Iterator<Integer> it = list.iterator();
        while (it.hasNext()) System.out.print(it.next() + " "); // 1 2 3 4 5
        System.out.println();

        // ListIterator – tiến & lùi
        ListIterator<Integer> li = list.listIterator();
        System.out.println("ListIterator forward:");
        while (li.hasNext()) System.out.print(li.next() + " "); // 1 2 3 4 5
        System.out.println("\nListIterator backward:");
        while (li.hasPrevious()) System.out.print(li.previous() + " "); // 5 4 3 2 1
        System.out.println();

        // ListIterator – thêm/sửa/xóa khi duyệt
        li = list.listIterator();
        while (li.hasNext()) {
            if (li.next() == 3) {
                li.set(30);      // sửa
                li.add(99);      // thêm trước vị trí sau 3 (con trỏ đã next)
            }
        }
        System.out.println("Sau sửa/thêm: " + list); // [1, 2, 30, 99, 4, 5]
    }
}

Kết quả

Iterator (forward): 1 2 3 4 5
ListIterator forward: 1 2 3 4 5
ListIterator backward: 5 4 3 2 1
Sau sửa/thêm: [1, 2, 30, 99, 4, 5]

Tóm lại: Dùng Iterator cho duyệt đọc đơn giản trên mọi Collection. Duyệt List cần thao tác index, thêm/sửa/xóa khi duyệt → dùng ListIterator.