The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object.
Syntax :
lastIndexOf(element)
Parameter : The element whose last index is to be returned.
Returns :
It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found.
Program to demonstrate the working of lastIndexOf():
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<Integer>( 7 );
arr.add( 10 );
arr.add( 20 );
arr.add( 30 );
arr.add( 40 );
arr.add( 30 );
arr.add( 30 );
arr.add( 40 );
System.out.println( "The list initially " + arr);
int element = arr.lastIndexOf( 30 );
if (element != - 1 )
System.out.println( "the lastIndexof of" +
" 30 is " + element);
else
System.out.println( "30 is not present in" +
" the list" );
element = arr.lastIndexOf( 100 );
if (element != - 1 )
System.out.println( "the lastIndexof of 100" +
" is " + element);
else
System.out.println( "100 is not present in" +
" the list" );
}
}
|
Output :
The list initially [10, 20, 30, 40, 30, 30, 40]
the lastIndexof of 30 is 5
100 is not present in the list
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Nov, 2018
Like Article
Save Article