Java Arraylist Lastindexof
# Java ArrayList lastIndexOf() Method
[ Java ArrayList](#)
The lastIndexOf() method returns the index of the last occurrence of the specified element in the dynamic array (ArrayList).
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 in the array.
If the specified element does not exist in the dynamic array, the lastIndexOf() method returns -1.
### Example
Get the index of the last occurrence of an element in an ArrayList:
## Example
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// Create an array
ArrayList sites =new ArrayList();
sites.add("Google");
sites.add("");
sites.add("Taobao");
sites.add("");
System.out.println("Website list: "+ sites);
// Get the last occurrence of
int position1 = sites.lastIndexOf("");
System.out.println("Last occurrence of : "+ position1);
// Wiki is not in the arraylist
// Returns -1
int position2 = sites.lastIndexOf("Wiki");
System.out.println("Last occurrence of Wiki: "+ position2);
}
}
The output of the above program is:
Website list: [Google, , Taobao, ]Last occurrence of : 3Last occurrence of Wiki: -1
In the example above, we created a dynamic array named sites.
Note these expressions:
// Returns 3 sites.lastIndexOf("");// Wiki is not in the dynamic array, returns -1 sites.lastIndexOf("Wiki");
The lastIndexOf() method successfully returned the last occurrence of (which is 3). The element Wiki does not exist in the arraylist. Therefore, the method returns -1.
If we want to get the index of the first occurrence of , we can use the indexOf() method. To learn more, please visit [Java ArrayList indexOf()](#) .
**Note:** We can also use the [Java ArrayList get()](#) method to get the element at a specified index position.
[ Java ArrayList](#)
YouTip