Java中的 ArrayBlockingQueue clear() 方法
ArrayBlockingQueue是有界的阻塞队列,它在内部存储由数组支持的元素。
- ArrayBlockingQueue类是Java集合框架的成员。
- 有界意味着它将具有固定大小,您不能存储数量超过队列容量的元素。
- 队列还遵循 FIFO(先进先出)规则来存储和删除队列中的元素。
- 如果你试图将一个元素放入一个满队列或从一个空队列中取出一个元素,那么队列会阻止你。
clear()方法从此队列中删除所有元素。应用此方法后,队列将变为空。
句法:
public void clear()
下面的程序说明了 ArrayBlockingQueue 的 clear() 方法。
示例 1
// Java Program Demonstrate clear()
// method of ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
public class GFG {
public static void main(String[] args)
{
// define capacity of ArrayBlockingQueue
int capacity = 5;
// create object of ArrayBlockingQueue
ArrayBlockingQueue queue
= new ArrayBlockingQueue(capacity);
// Add element to ArrayBlockingQueue
queue.add(23);
queue.add(32);
queue.add(45);
queue.add(12);
// print queue after adding numbers
System.out.println("After addding numbers");
System.out.println(queue);
// Apply clear() method
queue.clear();
// print queue after clear() operation
System.out.println("After clear() method");
System.out.println(queue);
}
}
Output :
After addding numbers
[23, 32, 45, 12]
After clear() method
[]
示例 2
// Java Program Demonstrate clear()
// method of ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
public class GFG {
public static void main(String[] args)
{
// define capacity of ArrayBlockingQueue
int capacity = 5;
// create object of ArrayBlockingQueue to store 5 names
ArrayBlockingQueue names
= new ArrayBlockingQueue(capacity);
// Add element to ArrayBlockingQueue
names.add("Aman");
names.add("Siddhant");
names.add("Mahafuj");
names.add("Raunak");
names.add("Suvo");
// print queue after adding numbers
System.out.println("List of Names: " + names);
System.out.println("Remaining Capacity: " + names.remainingCapacity());
// Apply clear() method
names.clear();
// print queue after clear() operation
System.out.println("List of Names: " + names);
System.out.println("Remaining Capacity: " + names.remainingCapacity());
}
}
Output :
List of Names: [Aman, Siddhant, Mahafuj, Raunak, Suvo]
Remaining Capacity: 0
List of Names: []
Remaining Capacity: 5
参考:
https://docs.oracle.com/javase/7/docs/api/java Java()