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.
public boolean contains(Object o)
The element to be checked for presence.
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))
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));}}
In the code above, we created a Stack object and added elements 1, 2, 3 to it using the push method.
We then used the contains(element) method to check if the element is present in the Stack object.
For the values 1 and 2, the contains method returns true. For the value 5, it returns false because 5 is not present in the Stack object.