Java Stack - indexOf() Method
The java.util.Stack.indexOf() method returns index of the first occurrence of the specified element in this stack, searching forward from specified index. It returns -1 if element is not present in the stack.
Syntax
public int indexOf(Object o, int index)
Parameters
o |
Specify the element to search for in the stack. |
index |
Specify index to search searching from. |
Return Value
Returns the index of the first occurrence of the specified element in the stack, searching forward from specified index, 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, searching forward from specified index.
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 after index=2 at index="); System.out.print(MyStack.indexOf(30, 2)); } }
The output of the above code will be:
30 appeared first time after index=2 at index=4
❮ Java.util - Stack