Java – Get Index of Specific Element in ArrayList
To get the index of specific element in ArrayList in Java, use ArrayList.indexOf() method.
ArrayList.indexOf() returns the index of the first occurrence of the specified object/element in this ArrayList, or -1 if this ArrayList does not contain the element.
Reference for Syntax & Examples – ArrayList.indexOf()
Now, let us go through an example, where we will find the index of string "cd"
in an ArrayList.
Java Program
</>
Copy
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("ab");
arrayList.add("bc");
arrayList.add("cd");
arrayList.add("de");
arrayList.add("cd");
Object obj = "cd";
int index = arrayList.indexOf(obj);
System.out.println("The index is : " + index);
}
}
Output
The index is : 2
Conclusion
In this Java Tutorial, we learned how to get the index of first occurrence of a specified element in ArrayList.