Write a Java program to Check if two queues are equal. Two queues are considered equal if they have the same elements in the same order


The Java code demonstrates how to check if two queues are equal in terms of their elements. Let's go through the code step by step:

  • Three Queue interfaces are implemented using the LinkedList class to create three queues named q1, q2, and q3 to store integers.
  • Integer elements (1, 2, 3) are added to q1, q2, and q3 using the offer() method.
  • The elements of q1, q2, and q3 are printed using System.out.println().
  • The areEqual() method is called twice to compare q1 with q2 and q1 with q3.
  • The result of the comparison is printed using System.out.println().

The areEqual() method is responsible for comparing two queues for equality. It works as follows:

  • The method first checks if the sizes of both queues are equal. If not, it returns false, as two queues with different sizes cannot be equal.
  • If the sizes of both queues are equal, the method uses two iterators (iterator1 and iterator2) to iterate over the elements of both queues.
  • It compares each element from q1 with the corresponding element from q2. If any pair of elements is not equal, the method returns false.
  • If all elements are found to be equal during the iteration, the method returns true, indicating that the queues are equal.

Source Code

import java.util.*;
 
public class QueueEquality
{
	public static boolean areEqual(Queue<Integer> q1, Queue<Integer> q2)
	{
		if (q1.size() != q2.size())
		{
			return false;
		}
 
		Iterator<Integer> iterator1 = q1.iterator();
		Iterator<Integer> iterator2 = q2.iterator();
 
		while (iterator1.hasNext())
		{
			if (!iterator1.next().equals(iterator2.next()))
			{
				return false;
			}
		}
 
		return true;
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> q1 = new LinkedList<>();
		q1.offer(1);
		q1.offer(2);
		q1.offer(3);
 
		Queue<Integer> q2 = new LinkedList<>();
		q2.offer(1);
		q2.offer(2);
		q2.offer(3);
 
		Queue<Integer> q3 = new LinkedList<>();
		q3.offer(3);
		q3.offer(2);
		q3.offer(1);
 
		System.out.println("Queue1 : " +q1);
		System.out.println("Queue2 : " +q2);
		System.out.println("Queue3 : " +q3);
		System.out.println("Queue1 and Queue2 equal ? " + areEqual(q1, q2));
		System.out.println("Queue1 and Queue3 equal ? " + areEqual(q1, q3));
	}
}
 

Output

Queue1 : [1, 2, 3]
Queue2 : [1, 2, 3]
Queue3 : [3, 2, 1]
Queue1 and Queue2 equal ? true
Queue1 and Queue3 equal ? false

Example Programs