Write a Java program to compare two queues


The Java code represents a program that compares two queues to check if they are equal. The queues are implemented using the LinkedList class from the java.util package. Let's go through the code step-by-step:

  • Two Queue objects called queue1 and queue2 are created, both using the LinkedList implementation.
  • Elements are added to queue1 using the add() method, and elements are added to queue2 using the same method.
  • The equals() method is used to compare queue1 and queue2. The equals() method is inherited from the AbstractCollection class, and in the context of Queue, it checks if both queues have the same elements in the same order.
  • The result of the comparison is stored in the isEqual variable.
  • Finally, the program prints whether the queues are equal or not based on the comparison result.

Source Code

import java.util.*;
public class CompareTwoQueues
{
	public static void main(String[] args)
	{
		Queue <String> queue1 = new LinkedList <>();
		Queue <String> queue2 = new LinkedList <>();
 
		// Add elements to the first queue
		queue1.add("Pink");
		queue1.add("Black");
		queue1.add("Blue");
 
		// Add elements to the second queue
		queue2.add("Pink");
		queue2.add("Black");
		queue2.add("Blue");
		queue2.add("White");
 
		// Compare the queues
		boolean isEqual = queue1.equals(queue2);
 
		if (isEqual)
		{
			System.out.println("The Queues are Equal.");
		}
		else
		{
			System.out.println("The Queues are Not Equal.");
		}
 
	}
}

Output

The Queues are Not Equal.

Example Programs