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

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

Java中的 PriorityBlockingQueue clear() 方法

PriorityBlockingQueueclear()方法从该队列中移除所有元素。因此,当需要清除 PriorityBlockingQueue 时,可以应用此方法。

句法:

public void clear()

范围:
此方法不带任何参数。

回报:
此方法不返回任何内容。

例外:
此方法不会抛出任何异常。

下面的程序说明了使用 clear() 方法从 PriorityBlockingQueue 中删除所有元素。

示例 1:

// Java Program to Demonstrate clear() method
// of PriorityBlockingQueue.
  
import java.util.concurrent.PriorityBlockingQueue;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // define capacity of PriorityBlockingQueue
        int capacity = 15;
  
        // create object of PriorityBlockingQueue
        PriorityBlockingQueue PrioBlockingQueue
            = new PriorityBlockingQueue(capacity);
  
        // add numbers
        PrioBlockingQueue.add(78758575);
        PrioBlockingQueue.add(63447688);
        PrioBlockingQueue.add(56434788);
  
        // print queue after add operation
        System.out.println("After Adding  Numbers:");
        System.out.println("PriorityBlockingQueue:"
                           + PrioBlockingQueue);
  
        // remove all the elements using clear() method
        PrioBlockingQueue.clear();
  
        // print queue after clear operation
        System.out.println("\nAfter clear operation:");
        System.out.println("PriorityBlockingQueue:"
                           + PrioBlockingQueue);
    }
}
输出:
After Adding  Numbers:
PriorityBlockingQueue:[56434788, 78758575, 63447688]

After clear operation:
PriorityBlockingQueue:[]

示例 2:说明包含名称列表的 PriorityBlockingQueue 上的 clear 方法。

// Java Program to Demonstrate clear() method
// of PriorityBlockingQueue.
  
import java.util.concurrent.PriorityBlockingQueue;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // define capacity of PriorityBlockingQueue
        int capacity = 15;
  
        // create object of PriorityBlockingQueue
        PriorityBlockingQueue PrioBlockingQueue
            = new PriorityBlockingQueue(capacity);
  
        // add some names
        PrioBlockingQueue.add("Tandrima");
        PrioBlockingQueue.add("Argha");
        PrioBlockingQueue.add("Arka");
  
        // print queue after add operation
        System.out.println("List of Names:");
        System.out.println("PriorityBlockingQueue: "
                           + PrioBlockingQueue);
  
        // remove all the elements using clear() method
        PrioBlockingQueue.clear();
  
        // print queue after clear operation
        System.out.println("\nAfter clearing List of names:");
        System.out.println("PriorityBlockingQueue:"
                           + PrioBlockingQueue);
    }
}
输出:
List of Names:
PriorityBlockingQueue: [Argha, Tandrima, Arka]

After clearing List of names:
PriorityBlockingQueue:[]

参考: https: Java/util/concurrent/PriorityBlockingQueue.html#clear–