The indexOf() method of CopyOnWriteArrayList class in Java

Java 8Object Oriented ProgrammingProgramming

The indexOf() method of the CopyOnWriteArrayList class is used to get the index of the first occurrence of an element. The method has two two forms. Let us see them one by one

indexOf(Object o) method

The indexOf(Object o) is used to get the index of the first occurrence of an element.

The syntax is as follows

indexOf(Object o)

Here, o is the element for which you want the index. To work with CopyOnWriteArrayList class, you need to import the following package

import java.util.concurrent.CopyOnWriteArrayList;

The following is an example to implement CopyOnWriteArrayList class indexOf() method in Java

Example

 Live Demo

import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
   public static void main(String[] args) {
      CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>();
      arrList.add(30);
      arrList.add(40);
      arrList.add(90);
      arrList.add(70);
      arrList.add(90);
      arrList.add(100);
      arrList.add(120);
      System.out.println("CopyOnWriteArrayList = " + arrList);
      System.out.println("HashCode of the CopyOnWriteArrayList class = " + arrList.indexOf(90));
   }
}

Output

CopyOnWriteArrayList = [30, 40, 90, 70, 90, 100, 120]
HashCode of the CopyOnWriteArrayList class = 2

indexOf(E e, int index) method

The indexOf(E e, int index) method of the CopyOnWriteArrayList class gets the index of the first occurrence of an element, but the search begins from the index set as a parameter.

The syntax is as follows

indexOf(E ele, int index)

Here, ele is the element to search for, whereas the index is the index from where the search will start. To work with CopyOnWriteArrayList class, you need to import the following package

import java.util.concurrent.CopyOnWriteArrayList;

The following is an example to implement CopyOnWriteArrayList class indexOf() method in Java

Example

 Live Demo

import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
   public static void main(String[] args) {
      CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>();
      arrList.add(30);
      arrList.add(90);
      arrList.add(80);
      arrList.add(70);
      arrList.add(90);
      arrList.add(100);
      arrList.add(120);
      System.out.println("CopyOnWriteArrayList = " + arrList);
      System.out.println("HashCode of the CopyOnWriteArrayList class = " + arrList.indexOf(90,3 ));
   }
}

Output

CopyOnWriteArrayList = [30, 90, 80, 70, 90, 100, 120]
HashCode of the CopyOnWriteArrayList class = 4
raja
Published on 26-Mar-2019 12:51:16
Advertisements