📜  Java中的 ArrayBlockingQueue iterator() 方法

📅  最后修改于: 2022-05-13 01:55:25.764000             🧑  作者: Mango

Java中的 ArrayBlockingQueue iterator() 方法

ArrayBlockingQueue类的iterator()方法用于以适当的顺序返回与该队列相同元素的迭代器。此方法返回的元素包含从 first(head) 到 last(tail) 顺序的元素。返回的迭代器是弱一致的。

句法:

public Iterator iterator()

返回值:该方法以正确的顺序返回与 ArrayBlockingQueue 中存在的元素相同的迭代器。

下面的程序说明了 ArrayBlockingQueue 类的 iterator() 方法:

方案一:

// Program Demonstrate how to apply iterator() method
// of ArrayBlockingQueue Class.
  
import java.util.concurrent.ArrayBlockingQueue;
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // Define capacity of ArrayBlockingQueue
        int capacity = 5;
  
        // Create object of ArrayBlockingQueue
        ArrayBlockingQueue queue = new 
                ArrayBlockingQueue(capacity);
  
        // Add 5 elements to ArrayBlockingQueue
        queue.offer(423);
        queue.offer(422);
        queue.offer(421);
        queue.offer(420);
        queue.offer(424);
  
        // Print queue
        System.out.println("Queue is " + queue);
  
        // Call iterator() method and Create an iterator
        Iterator iteratorValues = queue.iterator();
  
        // Print elements of iterator
        System.out.println("\nThe iterator values:");
        while (iteratorValues.hasNext()) {
            System.out.println(iteratorValues.next());
        }
    }
}
输出:
Queue is [423, 422, 421, 420, 424]

The iterator values:
423
422
421
420
424

方案二:

// Program Demonstrate how to apply iterator() method
// of ArrayBlockingQueue Class.
  
import java.util.concurrent.ArrayBlockingQueue;
import java.util.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // Define capacity of ArrayBlockingQueue
        int capacity = 5;
  
        // Create object of ArrayBlockingQueue
        ArrayBlockingQueue queue = new 
                  ArrayBlockingQueue(capacity);
  
        // Add 5 elements to ArrayBlockingQueue
        queue.offer("User");
        queue.offer("Employee");
        queue.offer("Manager");
        queue.offer("Analyst");
        queue.offer("HR");
  
        // Print queue
        System.out.println("Queue is " + queue);
  
        // Call iterator() method and Create an iterator
        Iterator iteratorValues = queue.iterator();
  
        // Print elements of iterator
        System.out.println("\nThe iterator values:");
        while (iteratorValues.hasNext()) {
            System.out.println(iteratorValues.next());
        }
    }
}
输出:
Queue is [User, Employee, Manager, Analyst, HR]

The iterator values:
User
Employee
Manager
Analyst
HR

参考: https: Java/util/concurrent/ArrayBlockingQueue.html#iterator