ArrayBlockingQueue類的iterator()方法用於按適當順序返回與此隊列相同元素的迭代器。從此方法返回的元素按從first(head)到last(tail)的順序包含元素。返回的迭代器是弱一致性的。
用法:
public Iterator iterator()
返回值:該方法以正確的順序返回具有與ArrayBlockingQueue中存在的元素相同的元素的迭代器。
以下示例程序旨在說明ArrayBlockingQueue類的iterator()方法:
示例1:
// 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<Integer> queue = new
ArrayBlockingQueue<Integer>(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
示例2:
// 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<String> queue = new
ArrayBlockingQueue<String>(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://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ArrayBlockingQueue.html#iterator
相關用法
- Java ArrayBlockingQueue contains()用法及代碼示例
- Java ArrayBlockingQueue add()用法及代碼示例
- Java ArrayBlockingQueue put()用法及代碼示例
- Java ArrayBlockingQueue take()用法及代碼示例
- Java ArrayBlockingQueue offer()用法及代碼示例
- Java ArrayBlockingQueue remainingCapacity()用法及代碼示例
- Java ArrayBlockingQueue drainTo()用法及代碼示例
- Java ArrayBlockingQueue remove()用法及代碼示例
- Java ArrayBlockingQueue toString()用法及代碼示例
- Java ArrayBlockingQueue spliterator()用法及代碼示例
- Java ArrayBlockingQueue clear()用法及代碼示例
- Java ArrayBlockingQueue size()用法及代碼示例
- Java ArrayBlockingQueue toArray()用法及代碼示例
- Java ArrayBlockingQueue poll()用法及代碼示例
- Java ArrayBlockingQueue peek()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 ArrayBlockingQueue iterator() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。