What is the Stack.indexOf(element, index) method in Java?

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

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:

  1. obj: The element to be searched.

  2. 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 the Stack class.

  • In line 4, we create a new object for Stack object with the name stack.

  • From lines 5-8, we use the push() method of the stack object to add four elements ("one","one", "one", "two") to the stack.

  • In line 10, we use the indexOf() method of the stack object to get the index of the first occurrence of the element one from index ‘1’. From index ‘1’ the element one is present at two indices: ‘1’ and ‘2’. We get 1 as a result because that is the first occurrence from index ‘1’.

  • In line 11, we use the indexOf() method of the stack object to get the index of the first occurrence of the element one from index 3. From index 3 the element one is not present so -1 will be returned.

Free Resources