Java Utility Library

Java Stack - lastIndexOf() Method



The java.util.Stack.lastIndexOf() method returns index of the last occurrence of the specified element in this stack. It returns -1 if element is not present in the stack.

Syntax

public int lastIndexOf(Object o)

Parameters

o Specify the element to search for in the stack.

Return Value

Returns the index of the last occurrence of the specified element in the stack, 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.

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 at index=" + MyStack.lastIndexOf(30)); 
  }
}

The output of the above code will be:

30 appeared last time at index=4

❮ Java.util - Stack