ArrayList lastIndexOf() method
In this tutorial, we will see the lastIndexOf()
method of the ArrayList class in Java. This method returns the index of the last occurrence of the specified element in this list.
Introduction
ArrayList is a widely used class to store and retrieve data in a collection framework.
Also, we have seen a few methods of the ArrayList class before like add()
, addAll()
, remove()
, set()
, iterate()
, clear()
, contains()
, get()
, removeRange()
, retainAll()
, trimToSize()
and indexOf()
method.
Today we will see the lastIndexOf(Object o)
method.
ArrayList lastIndexOf(Object o)
method
We know the important features of the list that it maintains the insertion order of the elements. Also, it allows duplicate elements in the list.
So, when we try to find any elements , there are chances that the same elements may present in the list multiple times at multiple index.
The lastIndexOf(Object o)
method returns the index of the last occurrences of the object specified. It returns -1 if the specified object o
is not present in the list.
The method is signature is given below.
1
public int lastIndexOf(Object o)
The lastIndexOf()
method accepts only one parameter, the Object o
whose index of the last occurrence will be returned.
The method has a return type as a int
. It returns the index of the last occurrences of the object specified as an int
. If the specified object o
is not present in the list, it will return -1.
Let’s see the java program for better understanding.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* A java program to explain the lastIndexOf() method
* of the arrayList class in java.
*
* @author Gaurav Kukade
*/
public class ArrayListLastIndexOfExample {
public static void main(String[] args) {
// create an empty arraylist object 'states'
List<String> states = new ArrayList<String>();
// add state in the arraylist, Florida multiple times
states.add("California");
states.add("Texas");
states.add("Florida");
states.add("Florida");
states.add("New Jersey");
states.add("Washington");
states.add("Florida");
int index = states.lastIndexOf("Florida");
//prints index of the last occurrences of Florida i.e. 6
System.out.println("The last index of the Florida: "+ index);
//trying get the index of element, which is not present
int index2 = states.lastIndexOf("Alaska");
System.out.println("The index of the Alaska: " + index2);
}
}
Output:
1
2
The index of the Florida: 6
The index of the Alaska: -1
Conclusion
1
public int lastIndexOf(Object o)
The lastIndexOf(Object o)
method returns the index of the last occurrences of the object specified. If the specified object o
is not present in the list, it returns the -1.
The example java program used in the above article can be found at this GitHub repository.
Please write your thoughts in the comment section below.
Join Newsletter
Get the latest tutorials right in your inbox. We never spam!