Write a Java program to get the size of the Queue collection


The Java code defines a class named QueueSize that demonstrates how to use the Queue interface to create and manipulate a queue using the LinkedList implementation. Here's a step-by-step explanation of the code:

  • Import statements: The code imports the java.util package, which includes the necessary classes to work with queues and lists.
  • QueueSize class: This is the main class that contains the main method.
  • Queue instantiation: The code creates a Queue object named queue_list using the LinkedList class. Since LinkedList implements the Queue interface, it can be used to create a queue.
  • Queue elements: The code adds several elements (strings) to the queue using the add method.
  • Printing the queue: The code prints the elements of the queue using System.out.println.
  • Getting the size of the queue: The code calculates the size of the queue using the size method and stores it in the variable size.
  • Printing the size: Finally, the code prints the size of the queue using System.out.println.

Source Code

import java.util.*;
public class QueueSize
{
	public static void main(String[] args)
	{
		Queue < String > queue_list = new LinkedList < > ();
		queue_list.add("Orange");
		queue_list.add("Yellow");
		queue_list.add("Green");
		queue_list.add("Pink");
		queue_list.add("Black");
		queue_list.add("Blue");
		queue_list.add("White");
		queue_list.add("Red");
 
		System.out.println("Queue Elements : " +queue_list );
 
		// Get the size of the queue
		int size = queue_list.size();
		System.out.println("Size of the Queue : " + size);
 
	}
}

Output

Queue Elements : [Orange, Yellow, Green, Pink, Black, Blue, White, Red]
Size of the Queue : 8

Example Programs