Java Utility Library

Java Stack - indexOf() Method



The java.util.Stack.indexOf() method returns index of the first occurrence of the specified element in this stack. It returns -1 if element is not present in the stack.

Syntax

public int indexOf(Object o)

Parameters

o Specify the element to search for in the stack.

Return Value

Returns the index of the first occurrence of the specified element in the stack, or -1 if element is not present in the stack.

Exception

NA.

Example:

In the example below, the java.util.Stack.indexOf() method is used to find the index of first occurrence of the specified element in the stack MyStack.

import java.util.*;

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

    //populating stack
    MyStack.push(10);
    MyStack.push(30);
    MyStack.push(20);
    MyStack.push(50);
    MyStack.push(30);

    System.out.print("30 appeared first time at index=" + MyStack.indexOf(30)); 
  }
}

The output of the above code will be:

30 appeared first time at index=1

❮ Java.util - Stack