Java ArrayList lastIndexOf() Method
The lastIndexOf() method returns the last occurrence of the specified element in the dynamic array.
The syntax for the lastIndexOf() method is:
arraylist.lastIndexOf(Object obj)
Note: arraylist is an object of the ArrayList class.
Parameter Description:
- obj - The element to search for
Return Value
Returns the index of the last occurrence of the specified element in the dynamic array.
If the element obj appears multiple times in the dynamic array, it returns the index of the last occurrence of obj.
If the specified element does not exist in the dynamic array, the lastIndexOf() method returns -1.
Example
Get the last occurrence index of an element in an ArrayList:
Example
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// Create an array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
sites.add("tutorialpro");
System.out.println("Website List: " + sites);
// Get the last occurrence of tutorialpro
int position1 = sites.lastIndexOf("tutorialpro");
System.out.println("tutorialpro last occurrence: " + position1);
// Wiki is not in the arraylist
// Returns -1
int position2 = sites.lastIndexOf("Wiki");
System.out.println("Wiki last occurrence: " + position2);
}
}
Executing the above program outputs:
Website List: [Google, tutorialpro, Taobao, tutorialpro]
tutorialpro last occurrence: 3
Wiki last occurrence: -1
In the above example, we created a dynamic array named sites.
Note these expressions:
// Returns 3
sites.lastIndexOf("tutorialpro");
// Wiki is not in the dynamic array, returns -1
sites.lastIndexOf("Wiki");
The lastIndexOf() method successfully returns the last occurrence of tutorialpro (which is 3). The element Wiki does not exist in the arraylist. Therefore, the method returns -1.
If we want to get the first occurrence index of tutorialpro, we can use the indexOf() method. For more information, visit Java ArrayList indexOf().
Note: We can also use the Java ArrayList get() method to get the element at a specified index.