What is the Stack.contains method in Java?

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

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 Stack
Stack<Integer> Stack = new Stack<>();
// add elememts
Stack.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 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.

Free Resources