Learn how to get the index of first occurrence of an element in the ArrayList using ArrayList.indexOf() method. To get the index of the last occurrence of the same element, use the lastIndexOf() method.
1. ArrayList.indexOf() API
The indexOf() 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.
public int indexOf(Object o);
The indexOf() takes only a single argument object which needs to be searched in the list for its first occurrence position.
The indexOf() returns:
index– the index position of the element if the element is found.
-1– if the element is NOT found.
2. ArrayList.indexOf() Example
The following Java program gets the first index of an object in the arraylist. In this example, we are looking for the first occurrence of the string “alex” in the given list. Note that string “alex” is present in the list 3 times, but the method returns the index of the first occurrence.
Please note that list indices start from 0.
ArrayList<String> list = new ArrayList<>(Arrays.asList("alex", "brian", "charles","alex",","alex","harry")); int index = list.indexOf("alex"); System.out.println(index);
We can use this method to find if an object is present in the arraylist. If the object is present, then the return value will be greater than
Happy Learning !!
Read More: ArrayList Java Docs