Learn how to get the index of first occurrence of a element in the ArrayList. We will be using ArrayList.indexOf() method to get the first occurrence.
1. ArrayList.indexOf() method
This method returns the index of the first occurrence of the specified element in this list. It will return '-1'
if the list does not contain the element.
1.1. indexOf() method syntax
public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
1.2. indexOf() method parameter
object
– the object which needs to be searched in the list for it’s first index position.
1.3. indexOf() return value
Return value is of int
type.
index
– first index position of element if element is found.-1
– if element is NOT found.
2. ArrayList get index of element
Java program for how to get first index of object in arraylist. In this example, we are looking for first occurrence of string “brian” in the given list.
We can use this method to find if an object is present in arraylist. If the object is present then return value will be greater than '-1
‘.
Note – Please note that arraylist index starts from 0.
import java.util.ArrayList; import java.util.Arrays; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(Arrays.asList("alex", "brian", "charles","alex","dough","gary","alex","harry")); int firstIndex = list.indexOf("brian"); System.out.println(firstIndex); firstIndex = list.indexOf("hello"); System.out.println(firstIndex); } }
Program output.
1 -1
Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs
What happens if two objects in the list are the same. I know it would print the index of the first occurrence, but how could you make it print the second occurrence instead.
If there are only two, then you can use the lastIndexOf (obj) method to get the index of the second element