Home »
Java »
Java Programs
Java program to compare two Stack collections
Java example to compare two Stack collections.
Submitted by Nidhi, on April 25, 2022
Problem statement
In this program, we will create 3 Stack Collections with a few elements. Then we will compare the Stack collection using the equals() method and print the appropriate message.
Java program to compare two Stack collections
The source code to compare two Stack collections is given below. The given program is compiled and executed successfully.
// Java program to compare two Stack collections
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack stack1 = new Stack();
Stack stack2 = new Stack();
Stack stack3 = new Stack();
stack1.push(10);
stack1.push(20);
stack2.push(10);
stack2.push(20);
stack3.push(30);
stack3.push(40);
if (stack1.equals(stack2))
System.out.println("Stacks stack1 and stack2 are equal.");
else
System.out.println("Stacks stack1 and stack2 are not equal.");
if (stack2.equals(stack3))
System.out.println("Stacks stack2 and stack3 are equal.");
else
System.out.println("Stacks stack2 and stack3 are not equal.");
}
}
Output
Stacks stack1 and stack2 are equal.
Stacks stack2 and stack3 are not equal.
Explanation
In the above program, we imported the "java.io.*" and "java.util.*"packages to use the Stack collection class. Here, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program.
In the main() method, we created 3 Stack collections and add elements. Then we compared stack elements using the equals() method. The equals() method returns true if stacks contain the same elements otherwise it returns false.
Java Stack Programs »