What is the Stack.lastIndexOf(element, index) method in Java?
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
The lastIndexOf method of the Stack class will search for the specific element backwards from the specific index and return the first index at which the searching element is found.
Syntax
public int lastIndexOf(Object obj, int index);
Parameter
This method takes 2 arguments.
-
obj: The element to be searched. -
index: The index from which the element is to be searched backward.
Return value
When searching for the passed element backwards from the specific index, the first index at which the searching element is found is returned.
If the element is not present from the specified index, then -1 is returned.
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("one");stack.push("two");stack.push("two");stack.push("three");System.out.println("The stack is " + stack);System.out.println("Last Index of element 'two' from index 3 : " + stack.lastIndexOf("two", 3));System.out.println("Last Index of element 'four' from index 3 : " + stack.lastIndexOf("four", 3));}}
Explanation
In the code above:
-
In line number 1, we import the
Stackclass. -
In line number 4, we create a new object for
Stackobject with the namestack. -
From line numbers 5 to 8, we use the
pushmethod of thestackobject to add four elements ("one","two", "two", "three") to thestack. -
In line number 11, we use the
lastIndexOfmethod of thestackobject with the searching element astwoand3as the index. This method will search backwards for the elementtwofrom index3. The elementtwois present in two indices:1and2. We get2as a result, since that is the first occurrence from index3when searching backwards. -
In line number 12, we use the
lastIndexOfmethod of thestackobject with the searching element asfourand3as the index. This method will search backwards for the elementtwofrom index3. The elementfouris not present in the stack so-1is returned.