What is the Stack.lastIndexOf method in Java?
Overview
The Stack class is a
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
Stackclass. -
In line 4, we create a new object of
Stackwith the namestack. -
From lines 5 to 7, we use the
pushmethod of thestackobject to add three elements ("1","2","3") to thestack. -
In line 10, we use the
lastIndexOfmethod of thestackobject to get the index of the last occurrence of the element"1". The element"1"is present at two indices,0and2. We get2as a result since that is the last occurrence. -
In line 11, we use the
lastIndexOfmethod of thestackobject to get the index of the last occurrence of the element"2". The element"2"is only present at index1, so it is returned. -
In line 12, we use the
lastIndexOfmethod of thestackobject to get the index of the last occurrence of the element"3". The element"3"is not present in thestack, so the method returns-1.