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:
The areEqual() method is responsible for comparing two queues for equality. It works as follows:
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)); } }
Queue1 : [1, 2, 3] Queue2 : [1, 2, 3] Queue3 : [3, 2, 1] Queue1 and Queue2 equal ? true Queue1 and Queue3 equal ? false
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions