Java ArrayBlockingQueue clear() Method
The clear() method of ArrayBlockingQueue removes all the elements from the queue. The queue becomes empty after calling this method.
Syntax:
public void clear()
Program to show ArrayBlockingQueue clear() method
Let’s have a look at the program.
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ArrayBlockingQueueClearExample { public static void main(String[] args) { int capacity = 5; BlockingQueuesalaries = new ArrayBlockingQueue<>(capacity); salaries.add(20000); salaries.add(25000); salaries.add(15000); salaries.add(17000); salaries.add(19000); System.out.println("Queue elements: \n" + salaries); salaries.clear(); System.out.println("Queue after clearing all elements: \n" + salaries); } }
Output:
Queue elements: [20000, 25000, 15000, 17000, 19000] Queue after clearing all elements: []
Example:
The below example shows how clear() method removes all the user-defined objects from the queue.
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ClearDemo { public static void main(String[] args) { int capacity = 5; BlockingQueueemployees = new ArrayBlockingQueue<>(capacity); employees.add(new Employee(101, "Adam")); employees.add(new Employee(102, "Smith")); employees.add(new Employee(103, "John")); employees.add(new Employee(104, "Ricky")); for (Employee employee : employees) { System.out.println(employee); } employees.clear(); System.out.println("Queue after clearing all elements: \n" + employees); } }
Output:
Employee [employeeId=101, employeeName=Adam] Employee [employeeId=102, employeeName=Smith] Employee [employeeId=103, employeeName=John] Employee [employeeId=104, employeeName=Ricky] Queue after clearing all elements: []
That’s all regarding the ArrayBlockingQueue clear method in Java. Please share if you find this article helpful.