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:
CopyOnWriteArrayListis a thread-safe version of anArrayList. For all the write operations likeaddandset,CopyOnWriteArrayListmakes a fresh copy underlying array and performs the operation in the cloned array. Due to this, the performance is lower when compared toArrayList. Read more aboutCopyOnWriteArrayListhere.
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 objectsCopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();// add elements to the listlist.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 listSystem.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
CopyOnWriteArrayListclass. -
Line 5: We create a
CopyOnWriteArrayListobject with the namelist. -
Lines 7–9: We use the
add()method of thelistobject to add three elements,"1","2","3", to the list. -
Line 13: We use the
indexOf()method of thelistobject to get the index of the first occurrence of the element"1". The element"1"is present at two indices,0and2. We get0as a result since that is the first occurrence. -
Line 14: We use the
indexOf()method of thelistobject to get the index of the first occurrence of the element"2". The element"2"is only present at index1, so1is returned. -
Line 15: We use the
indexOf()method of thelistobject to get the index of the first occurrence of the element"3". The element"3"is not present in the list, so-1is returned.