What is the Stack.indexOf(element, index) method in Java?
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
The indexOf() method of the Stack class will search for the specific element from the specific index and return the index at which the searching element is found first.
Syntax
public int indexOf(Object obj, int index);
Parameter
This method takes two arguments:
-
obj: The element to be searched. -
index: The index after which the element is to be searched.
Return value
Returns the index of the first occurance of the passed element at or after the passed index.
If the element is not present after the specified index , then -1 is returned.
Code
The code below demonstrates how to use the indexOf() method:
import java.util.Stack;class IndexOfExample {public static void main( String args[] ) {Stack<String> stack = new Stack<>();stack.push("one");stack.push("one");stack.push("one");stack.push("two");System.out.println("The stack is " + stack);System.out.println("First Index of element 'one' from index 1 : " + stack.indexOf("one", 1));System.out.println("First Index of element 'one' from index 3 : " + stack.indexOf("one", 3));}}
Explanation
In the above code:
-
In line
1, we import theStackclass. -
In line
4, we create a new object forStackobject with the namestack. -
From lines
5-8, we use thepush()method of thestackobject to add four elements ("one","one", "one", "two") to thestack. -
In line
10, we use theindexOf()method of thestackobject to get the index of the first occurrence of the elementonefrom index ‘1’. From index ‘1’ the elementoneis present at two indices: ‘1’ and ‘2’. We get1as a result because that is the first occurrence from index ‘1’. -
In line 11, we use the
indexOf()method of thestackobject to get the index of the first occurrence of the elementonefrom index3. From index3the elementoneis not present so-1will be returned.