Q:

Java program to compare two Stack collections

belongs to collection: Java Stack Programs

0

Java program to compare two Stack collections

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to convert a Stack collection into an... >>
<< Java program to get the topmost element from Stack...