当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ArrayBlockingQueue iterator()用法及代码示例


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



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 ArrayBlockingQueue iterator() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。