What is the Stack.lastIndexOf method in Java?

Overview

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 lastIndexOf method is used to get the index of the last occurrence of the specified element in the Stack object.

Syntax

public int lastIndexOf(Object o);

Parameters

This method takes the element to be searched in the stack as a parameter.

Return value

lastIndexOf returns the last index at which the specified element is present in the stack. If the element is not present in the stack, then the method returns -1.

Code

The code below demonstrates how to use the lastIndexOf method.

import java.util.Stack;
class LastIndexOfExample {
public static void main( String args[] ) {
Stack<String> stack = new Stack<>();
stack.push("1");
stack.push("2");
stack.push("1");
System.out.println("The stack is " + stack);
System.out.println("Last Index of element '1' is : " + stack.lastIndexOf("1"));
System.out.println("Last Index of element '2' is : " + stack.lastIndexOf("2"));
System.out.println("Last Index of element '3' is : " + stack.lastIndexOf("3"));
}
}

Explanation

In the code above:

  • In line 1, we import the Stack class.

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

  • From lines 5 to 7, we use the push method of the stack object to add three elements ("1","2","3") to the stack.

  • In line 10, we use the lastIndexOf method of the stack object to get the index of the last occurrence of the element "1". The element "1" is present at two indices, 0 and 2. We get 2 as a result since that is the last occurrence.

  • In line 11, we use the lastIndexOf method of the stack object to get the index of the last occurrence of the element "2". The element "2" is only present at index 1, so it is returned.

  • In line 12, we use the lastIndexOf method of the stack object to get the index of the last occurrence of the element "3". The element "3" is not present in the stack, so the method returns -1.

Free Resources