AbstractList lastIndexOf() method in Java with Examples
The lastIndexOf() method of java.util.AbstractList class is used to return the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
Syntax:
public int lastIndexOf(Object o)
Parameters: This method takes Object o as a parameter which is the element to search for.
Returns Value: This method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
Exception: This method throws NullPointerException if the specified element is null and this list does not permit null elements.
Below are the examples to illustrate the lastIndexOf() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
AbstractList<String>
arrlist1 = new ArrayList<String>();
arrlist1.add( "A" );
arrlist1.add( "B" );
arrlist1.add( "A" );
arrlist1.add( "B" );
arrlist1.add( "E" );
System.out.println( "ArrayList : "
+ arrlist1);
int lastindex = arrlist1.lastIndexOf( "A" );
System.out.println( "Last index of A : "
+ lastindex);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
ArrayList : [A, B, A, B, E]
Last index of A : 2
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
AbstractList<String> arrlist1 = null ;
System.out.println( "ArrayList : "
+ arrlist1);
System.out.println( "\nTrying to get"
+ " the index from"
+ " null ArrayList" );
int lastindex = arrlist1.lastIndexOf( "B" );
System.out.println( "Last index of B : "
+ lastindex);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
ArrayList : null
Trying to get the index from null ArrayList
Exception thrown : java.lang.NullPointerException
Last Updated :
21 Nov, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...