Giao diện lặp lại Java

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về giao diện Java Iterator với sự trợ giúp của một ví dụ.

Các Iteratorgiao diện của khuôn khổ bộ sưu tập Java cho phép chúng ta truy cập các yếu tố của một bộ sưu tập. Nó có một giao diện con ListIterator.

Tất cả các bộ sưu tập Java đều bao gồm một iterator()phương thức. Phương thức này trả về một thể hiện của trình lặp được sử dụng để lặp qua các phần tử của bộ sưu tập.

Các phương thức của lặp lại

Các Iteratorgiao diện cung cấp 4 phương pháp có thể được sử dụng để thực hiện các hoạt động khác nhau trên các yếu tố của bộ sưu tập.

  • hasNext() – returns true if there exists an element in the collection
  • next() – returns the next element of the collection
  • remove() – removes the last element returned by the next()
  • forEachRemaining() – performs the specified action for each remaining element of the collection

Ví dụ: Triển khai lặp lại

Trong ví dụ dưới đây, chúng tôi đã triển khai hasNext()next(), remove()và forEachRemining()phương pháp của Iteratorgiao diện trong một array list.

import java.util.ArrayList;
import java.util.Iterator;

class Main {
    public static void main(String[] args) {
        // Creating an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(3);
        numbers.add(2);
        System.out.println("ArrayList: " + numbers);

        // Creating an instance of Iterator
        Iterator<Integer> iterate = numbers.iterator();

        // Using the next() method
        int number = iterate.next();
        System.out.println("Accessed Element: " + number);

        // Using the remove() method
        iterate.remove();
        System.out.println("Removed Element: " + number);

        System.out.print("Updated ArrayList: ");

        // Using the hasNext() method
        while(iterate.hasNext()) {
            // Using the forEachRemaining() method
            iterate.forEachRemaining((value) -> System.out.print(value + ", "));
        }
    }
}

Đầu ra

ArrayList: [1, 3, 2]
Acessed Element: 1
Removed Element: 1
Updated ArrayList: 3, 2,

Trong ví dụ trên, hãy chú ý câu lệnh:

iterate.forEachRemaining((value) -> System.put.print(value + ", "));

Ở đây, chúng ta đã chuyển biểu thức lambda làm đối số của forEachRemaining()phương thức.

Bây giờ phương thức sẽ in tất cả các phần tử còn lại của danh sách mảng.









Gõ tìm kiếm nhanh...