ADVERTISEMENT
ADVERTISEMENT

Java program to compare two Stack collections

Java example to compare two Stack collections.
Submitted by Nidhi, on April 25, 2022

Problem Solution:

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.

Program/Source Code:

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.