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


Java PriorityBlockingQueue size()用法及代码示例


PriorityBlockingQueue的size()方法用于查找队列的当前大小。它返回集合中元素的数量。如果集合包含多个Integer.MAX_VALUE元素,则此方法返回Integer.MAX_VALUE。

用法:

public int size()

返回值:此方法返回此PriorityBlockingQueue中存在的元素数


下面是说明PriorityBlockingQueue的size()方法的程序:

示例1:

// Java program to demonstrate 
// size() method 
  
import java.util.concurrent.PriorityBlockingQueue; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create object of PriorityBlockingQueue 
        PriorityBlockingQueue<String> pbq 
            = new PriorityBlockingQueue<String>(); 
  
        // Add element to PriorityBlockingQueue 
        pbq.put("1"); 
        pbq.put("2"); 
        pbq.put("3"); 
        pbq.put("4"); 
  
        // print queue 
        System.out.println("Queue:  " + pbq); 
        System.out.println("Queue Size:  " + pbq.size()); 
    } 
}
输出:
Queue:  [1, 2, 3, 4]
Queue Size:  4

示例2:演示size()用于动态更改队列。

// Java program to demonstrate  
// size() method  
  
import java.util.concurrent.PriorityBlockingQueue; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create object of PriorityBlockingQueue 
        PriorityBlockingQueue<String> pbq 
            = new PriorityBlockingQueue<String>(); 
  
        // Add element to PriorityBlockingQueue 
        pbq.put("1"); 
        pbq.put("2"); 
        pbq.put("3"); 
        pbq.put("4"); 
  
        // print queue 
        System.out.println("Queue:  " + pbq); 
        System.out.println("Queue Size:  " + pbq.size()); 
  
        // remove 2 
        boolean res = pbq.remove("2"); 
        System.out.println("\n2 removed: " + res); 
  
        // print queue 
        System.out.println("Queue:  " + pbq); 
        System.out.println("Queue Size:  " + pbq.size()); 
  
        // add  5 
        pbq.put("5"); 
  
        // print queue 
        System.out.println("\n5 added"); 
        System.out.println("Queue:  " + pbq); 
        System.out.println("Queue Size:  " + pbq.size()); 
    } 
}
输出:
Queue:  [1, 2, 3, 4]
Queue Size:  4

2 removed: true
Queue:  [1, 4, 3]
Queue Size:  3

5 added
Queue:  [1, 4, 3, 5]
Queue Size:  4


相关用法


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