Write a Java program to compare two Stack collections


The code demonstrates how to compare stacks for equality in Java using the equals method. Let's go through the code step by step:

  • The code begins by importing the necessary libraries: java.io.* and java.util.* .
  • The Copmare_Stack class is defined, serving as the entry point of the program.
  • In the main method, three stack objects are created using the raw Stack class: sta1, sta2, and sta3. It is important to note that using raw types is not recommended, and it's better to use generics to specify the type of elements in the stack.
  • Strings "Pink," "Yellow," and "Blue" are pushed onto sta1 using the push method.
  • Strings "Green" and "Red" are pushed onto sta2 using the push method.
  • Strings "Pink," "Yellow," and "Blue" are pushed onto sta3 using the push method.
  • The equals method is used to compare sta1 and sta3 for equality. If they are equal, the code prints "Stacks 1 and 3 are Equal." Otherwise, it prints "Stacks 1 and 3 are Not Equal."
  • The equals method is used again to compare sta2 and sta3 for equality. If they are equal, the code prints "Stacks 2 and 3 are Equal." Otherwise, it prints "Stacks 2 and 3 are Not Equal."

Source Code

import java.io.*;
import java.util.*;
public class Compare_Stack
{
	public static void main(String[] args)
	{
		Stack sta1 = new Stack();
		Stack sta2 = new Stack();
		Stack sta3 = new Stack();
 
		sta1.push("Pink");
		sta1.push("Yellow");
		sta1.push("Blue");
 
		sta2.push("Green");
		sta2.push("Red");
 
		sta3.push("Pink");
		sta3.push("Yellow");
		sta3.push("Blue");
 
		if (sta1.equals(sta3))
		{
			System.out.println("Stacks 1 and 3 are Equal.");
		}
		else
		{
			System.out.println("Stacks 1 and 3 are Not Equal.");
		}
 
		if (sta2.equals(sta3))
		{
			System.out.println("Stacks 2 and 3 are Equal.");
		}
		else
		{
			System.out.println("Stacks 2 and 3 are Not Equal.");
		}
	}
}

Output

Stacks 1 and 3 are Equal.
Stacks 2 and 3 are Not Equal.