📌  相关文章
📜  Java中的 PriorityBlockingQueue size() 方法

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

Java中的 PriorityBlockingQueue size() 方法

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

句法:

public int size()

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

下面是说明 PriorityBlockingQueue 的 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 pbq
            = new PriorityBlockingQueue();
  
        // 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 pbq
            = new PriorityBlockingQueue();
  
        // 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