當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。