Write a Java program to remove all elements of queue


The Java code defines a class named RemoveAllElements that demonstrates how to clear all elements from a queue using the clear() method. Here's a step-by-step explanation of the code:

  • Import statements: The code imports the necessary classes from the java.util package to work with queues and lists.
  • RemoveAllElements class: This is the main class that contains the main method.
  • Queue instantiation: The code creates a Queue named queue_list using the LinkedList class.
  • Adding elements to the queue: The code adds several string elements to the queue_list using the add method.
  • Printing the queue elements before clearing: The code prints the elements of the queue using System.out.println. This will show the elements in the queue before they are cleared.
  • Clearing the queue: The code calls the clear() method on the queue_list. This method removes all elements from the queue, leaving it empty.
  • Printing the queue elements after clearing: The code prints the elements of the queue again after clearing it. Since the queue is empty now, the output will show an empty set of brackets.

Source Code

import java.util.LinkedList;
import java.util.Queue;
public class RemoveAllElements
{
	public static void main(String[] args)
	{
		Queue <String> queue_list = new LinkedList <>();
		queue_list.add("Yellow");
		queue_list.add("Green");
		queue_list.add("Pink");
		queue_list.add("Black");
		queue_list.add("Blue");
		queue_list.add("White");
 
		System.out.println("Queue Elements Before Clearing : " + queue_list);
 
		// Clear the queue
		queue_list.clear();
 
		System.out.println("Queue Elements After Clearing : " + queue_list);
	}
}

Output

Queue Elements Before Clearing : [Yellow, Green, Pink, Black, Blue, White]
Queue Elements After Clearing : []

Example Programs