The Java.util.Stack.lastIndexOf(Object element, int last_index) method is used to the last index of the first occurrence of the specified element in this Stack, searching forwards from last index, or returns -1 if the element is not found. More formally, returns the lowest last index i such that (i >= last index && Objects.equals(o, get(i))), or -1 if there is no such last index.
Syntax:
public int lastIndexOf(Object element,
int last_index)
Parameters: This method accepts two parameters:
- element of the type of Stack. It specifies the element whose occurrence is needed to be checked in the Stack.
- last index of the type Integer. It specifies the last index to start searching from
Return Value: This method returns the last index or position of the first occurrence of the element in the Stack from the specified last index. Else it returns -1 if the element is not present in the Stack. The returned value is of integer type.
Exception: This method throws IndexOutOfBoundsException if the specified index is greater than or equal to the current size of this vector
Below programs illustrate the Java.util.Stack.lastIndexOf() method:
Program 1:
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.add( "Geeks" );
stack.add( "for" );
stack.add( "Geeks" );
stack.add( "10" );
stack.add( "Geeks" );
System.out.println( "Stack: " + stack);
System.out.println( "The first occurrence"
+ " of Geeks is at last index:"
+ stack.indexOf( "Geeks" ));
System.out.println( "The last occurrence"
+ " of Geeks is at last index: "
+ stack
.lastIndexOf( "Geeks" ,
stack.lastIndexOf( "Geeks" )));
}
}
|
Output:
Stack: [Geeks, for, Geeks, 10, Geeks]
The first occurrence of Geeks is at last index:0
The last occurrence of Geeks is at last index: 4
Program 2: To demonstrate IndexOutOfBoundsException
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<Integer> stack = new Stack<Integer>();
stack.add( 1 );
stack.add( 2 );
stack.add( 3 );
stack.add( 10 );
stack.add( 20 );
System.out.println( "Stack: " + stack);
System.out.println( "The 10th occurrence"
+ " of Geeks is at index: " );
try {
stack.lastIndexOf( "Geeks" , 10 );
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
Stack: [1, 2, 3, 10, 20]
The 10th occurrence of Geeks is at index:
java.lang.IndexOutOfBoundsException: 10 >= 5
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
24 Dec, 2018
Like Article
Save Article