Stack equals() method in Java with Example
The Java.util.Stack.equals(Object obj) method of Stack class in Java is used verify the equality of an Object with a Stack and compare them. The list returns true only if both Stack contains same elements with same order.
Syntax:
first_Stack.equals(second_Stack)
Parameters: This method accepts a mandatory parameter second_Stack which refers to the second Stack to be compared to the first Stack.
Return value: The method returns true if the equality holds and both the objects and Stack are equal else it returns false.
Below programs are used to illustrate the working of the java.util.Stack.elements() method:
Program 1:
import java.util.*;
public class Stack_Demo {
public static void main(String[] args)
{
Stack<String> stack1 = new Stack<String>();
stack1.add( "Geeks" );
stack1.add( "4" );
stack1.add( "Geeks" );
stack1.add( "Welcomes" );
stack1.add( "You" );
System.out.println( "The Stack is: "
+ stack1);
Stack<String> stack2 = new Stack<String>();
stack2.add( "Geeks" );
stack2.add( "4" );
stack2.add( "Geeks" );
stack2.add( "Welcomes" );
stack2.add( "You" );
System.out.println( "The Stack is: "
+ stack2);
System.out.println( "Are both of them equal? "
+ stack1.equals(stack2));
}
}
|
Output:
The Stack is: [Geeks, 4, Geeks, Welcomes, You]
The Stack is: [Geeks, 4, Geeks, Welcomes, You]
Are both of them equal? true
Program 2 :
import java.util.*;
public class Stack_Demo {
public static void main(String[] args)
{
Stack<Integer> stack1 = new Stack<Integer>();
stack1.add( 10 );
stack1.add( 15 );
stack1.add( 20 );
stack1.add( 25 );
stack1.add( 30 );
System.out.println( "The Stack is: " + stack1);
Stack<Integer> stack2 = new Stack<Integer>();
stack2.add( 10 );
stack2.add( 15 );
stack2.add( 20 );
stack2.add( 25 );
stack2.add( 30 );
stack2.add( 40 );
System.out.println( "The Stack is: " + stack2);
System.out.println( "Are both of them equal? "
+ stack1.equals(stack2));
}
}
|
Output:
The Stack is: [10, 15, 20, 25, 30]
The Stack is: [10, 15, 20, 25, 30, 40]
Are both of them equal? false
Last Updated :
24 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...