What is the Stack.contains method in Java?
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
The contains() method of the Stack class can be used to check if an element is present in the Stack object.
Syntax
public boolean contains(Object o)
Argument
The element to be checked for presence.
Return value
This method returns true if the passed element is present in the Stack object. Otherwise, it returns false.
The element is matched using the equals method. Internally, the element and passed argument are matched using:
(argument==null ? element == null : argument.equals(element))
Code
import java.util.Stack;class StackContainsElementExample {public static void main( String args[] ) {// Creating StackStack<Integer> Stack = new Stack<>();// add elememtsStack.push(1);Stack.push(2);Stack.push(3);System.out.println("The Stack is : " + Stack);System.out.println("Checking if 1 is present : " + Stack.contains(1));System.out.println("Checking if 2 is present : " + Stack.contains(2));System.out.println("Checking if 5 is present : " + Stack.contains(5));}}
Explanation
-
In the code above, we created a
Stackobject and added elements1,2,3to it using thepushmethod. -
We then used the
contains(element)method to check if the element is present in theStackobject. -
For the values
1and2, thecontainsmethod returnstrue. For the value5, it returnsfalsebecause5is not present in theStackobject.