VOOZH about

URL: https://www.geeksforgeeks.org/java/copyonwritearraylist-lastindexof-method-in-java/

⇱ CopyOnWriteArrayList lastIndexOf() method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CopyOnWriteArrayList lastIndexOf() method in Java

Last Updated : 11 Jul, 2025

The lastIndexOf(Object o) method of CopyOnWriteArrayList returns the last occurrence of the element passed in the list. It returns -1 if the element is not present in the list. 

Syntax: 

public int lastIndexOf(Object o)

Parameters: The function accepts a parameter o whose last occurrence is to be returned. 

Return Value: The function returns the last occurrence of the element. It returns -1 if the element is not present in the list. 

Below programs illustrate the above function: 

Program 1: 

Output:
CopyOnWriteArrayList: [32, 67, 67, 100]
lastIndexOf value: 2

Program 2: 

Output:
CopyOnWriteArrayList: [32, 67, 67, 100]
lastIndexOf value: -1

The lastIndexOf(E e, int index) method of CopyOnWriteArrayList returns the last occurrence of the element passed in the list after position index. It returns -1 if the element is not present in the list. 

Syntax: 

public int lastIndexOf(E e, int index)

Parameters: The function accepts two parameters which are described below:

  • index: specifies the index from which the occurrence is to be searched.
  • e: specifies the element whose last occurrence from position index is to be returned.

Return Value: The function returns the last occurrence of the element after position index. It returns -1 if the element is not present in the list.

Exceptions: The function throws an IndexOutOfBoundsException if the specified index is negative.

Below programs illustrate the above function:

Program 1:

Output:

CopyOnWriteArrayList: [32, 67, 67, 67]
lastIndexOf value: 2

Program 2:

Output:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.concurrent.CopyOnWriteArrayList.lastIndexOf(CopyOnWriteArrayList.java:198)
at java.util.concurrent.CopyOnWriteArrayList.lastIndexOf(CopyOnWriteArrayList.java:263)
at GFG.main(GFG.java:24)

Comment