Java Stack - lastIndexOf() Method
The java.util.Stack.lastIndexOf() method returns index of the last occurrence of the specified element in this stack, searching backward from specified index. It returns -1 if element is not present in the stack.
Syntax
public int lastIndexOf(Object o, int index)
Parameters
o |
Specify the element to search for in the stack. |
index |
Specify index to search searching backward from. |
Return Value
Returns the index of the last occurrence of the specified element in the stack, searching backward from specified index, or -1 if element is not present in the stack.
Exception
NA.
Example:
In the example below, the java.util.Stack.lastIndexOf() method is used to find the index of last occurrence of the specified element in the stack MyStack, searching backward from specified index.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a stack Stack<Integer> MyStack = new Stack<Integer>(); //populating stack MyStack.push(10); MyStack.push(30); MyStack.push(20); MyStack.push(50); MyStack.push(30); System.out.print("30 appeared last time before index=2 at index="); System.out.print(MyStack.lastIndexOf(30, 2)); } }
The output of the above code will be:
30 appeared last time before index=2 at index=1
❮ Java.util - Stack