The Java.util.Stack.indexOf(Object element, int index) method is used to the index of the first occurrence of the specified element in this Stack, searching forwards from index, or returns -1 if the element is not found. More formally, returns the lowest index i such that (i >= index && Objects.equals(o, get(i))), or -1 if there is no such index.
public int indexOf(Object element, int index)
Parameters: This method accepts two parameters:
- element of the type of Stack. It specifies the element whose occurrence is needed to be checked in the Stack.
- index of the type Integer. It specifies the index to start searching from
Return Value: This method returns the index or position of the first occurrence of the element in the Stack from the specified index. Else it returns -1 if the element is not present in the Stack. The returned value is of integer type.
Exception: This method throws IndexOutOfBoundsException if the specified index is negative.
Below programs illustrate the Java.util.Stack.indexOf() method:
Stack: [Geeks, for, Geeks, 10, Geeks] The first occurrence of Geeks is at index:0 The second occurrence of Geeks is at index: 0
Program 2: To demonstrate IndexOutOfBoundsException
Stack: [1, 2, 3, 10, 20] The -1 occurrence of Geeks is at index: java.lang.ArrayIndexOutOfBoundsException: -1
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.