What is the Stack.search method in Java?

The search method of the Stack class is used to search for an element.

Syntax

public int search(Object o);

Return value

This method returns the distance between the topmost element and the matched element.

The distance of the topmost element is 1.

If more than one element is matched, search returns the element closest to the top of the stack (i.e. the matching element that is inserted last).

If no elements match, then search returns -1.

The search method uses the equals method to check for the equality of the stack object.

Code

The example below demonstrates the use of the search method:

import java.util.Stack;
class StackIsEmptyExample {
public static void main( String args[] ) {
// Creating Stack
Stack<Integer> stack = new Stack<>();
// add elements
stack.push(5);
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(20);
// Print Stack
System.out.println("The Stack is: " + stack);
System.out.println("Searching element 5 is: " + stack.search(5));
System.out.println("Searching element 20 is: " + stack.search(20));
System.out.println("Searching element 50 is: " + stack.search(50));
}
}

Explanation

In the code above, we create a Stack object (line 5) and push the elements 5,10,20,30,20 (lines 8-12) to it. We use the search method to get the distance of the element from the top of the stack. For the element 5, we get 5 because element 5 is present in the fifth position from the top of the stack. For the element 20, we get 1, and for the element 50, we get -1 because element 50 is not present in the stack.

Free Resources