What is the CopyOnWriteArrayList.indexOf method in Java?

Overview

The indexOf method of the CopyOnWriteArrayList class can be used to get the index of the first occurrence of the specified element in the list.

Note: CopyOnWriteArrayList is a thread-safe version of an ArrayList. For all the write operations like add and set, CopyOnWriteArrayList makes a fresh copy underlying array and performs the operation in the cloned array. Due to this, the performance is lower when compared to ArrayList. Read more about CopyOnWriteArrayList here.

Syntax

public int indexOf(Object obj);

Parameters

  • obj: The element to be searched for in the list.

Return value

This method returns the first index at which the specified element is present in the list.

If the element is not present in the list, then indexOf returns -1.

Code

The code below demonstrates how we can use the indexOf method.

import java.util.concurrent.CopyOnWriteArrayList;
class IndexOfExample {
public static void main( String args[] ) {
// create a CopyOnWriteArrayList object which can store string objects
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
// add elements to the list
list.add("1");
list.add("2");
list.add("1");
System.out.println("The list is " + list);
// use indexOf methods to check if the element is present in the list
System.out.println("First Index of element '1' is : " + list.indexOf("1"));
System.out.println("First Index of element '2' is : " + list.indexOf("2"));
System.out.println("First Index of element '3' is : " + list.indexOf("3"));
}
}

Code explanation

In the code given above:

  • Line 1: We import the CopyOnWriteArrayList class.

  • Line 5: We create a CopyOnWriteArrayList object with the name list.

  • Lines 7–9: We use the add() method of the list object to add three elements, "1","2","3", to the list.

  • Line 13: We use the indexOf() method of the list object to get the index of the first occurrence of the element "1". The element "1" is present at two indices, 0 and 2. We get 0 as a result since that is the first occurrence.

  • Line 14: We use the indexOf() method of the list object to get the index of the first occurrence of the element "2". The element "2" is only present at index 1, so 1 is returned.

  • Line 15: We use the indexOf() method of the list object to get the index of the first occurrence of the element "3". The element "3" is not present in the list, so -1 is returned.

Free Resources