Java Utility Library

Java Stack - search() Method



The java.util.Stack.search() method returns the position of the specified element in the stack. The position of top element is considered 1 and the method returns the distance from the top of the stack of the occurrence nearest the top of the stack. If the element is not present in the stack, it returns -1.

Syntax

public int search (Object obj)

Here, E is the type of element maintained by the container.


Parameters

obj Specify the element which need to be searched in the stack.

Return Value

Returns the 1-based position from the top of the stack where the element is located. It returns -1 if the element is not present in the stack.

Exception

NA

Example:

In the example below, the java.util.Stack.search() method is used to search the specified element in the stack called MyStack.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<Integer> MyStack = new Stack<Integer>();

    //populating stack
    for(int i=1; i<=10; i++) {
      MyStack.push(i*10);
    }

    //search element in the stack
    System.out.println(MyStack.search(20));
    System.out.println(MyStack.search(60));
    System.out.println(MyStack.search(55));
  }
}

The output of the above code will be:

9
5
-1

❮ Java.util - Stack