How to Find Index of Element in ArrayList in Java
To find the index of an element in a Java
ArrayList, use the indexOf() method. It returns the first position of the element or -1 if the element is not found.Syntax
The indexOf() method is called on an ArrayList object and takes one argument: the element you want to find. It returns an int representing the index of the element.
arrayList.indexOf(element): Returns the index of the first occurrence ofelement.- Returns
-1if the element is not found.
java
int index = arrayList.indexOf(element);Example
This example shows how to create an ArrayList of strings and find the index of a specific element using indexOf(). It prints the index or a message if the element is not found.
java
import java.util.ArrayList; public class FindIndexExample { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); fruits.add("Date"); String searchFruit = "Cherry"; int index = fruits.indexOf(searchFruit); if (index != -1) { System.out.println(searchFruit + " found at index: " + index); } else { System.out.println(searchFruit + " not found in the list."); } } }
Output
Cherry found at index: 2
Common Pitfalls
Some common mistakes when using indexOf() include:
- Expecting
indexOf()to find elements by content when the elements are custom objects without properly overriddenequals()method. - Not checking for
-1which means the element was not found. - Using
indexOf()on a list with duplicate elements returns only the first occurrence.
Always ensure your objects have equals() defined if you want to find them by value.
java
import java.util.ArrayList; class Person { String name; Person(String name) { this.name = name; } } public class PitfallExample { public static void main(String[] args) { ArrayList<Person> people = new ArrayList<>(); people.add(new Person("Alice")); people.add(new Person("Bob")); Person searchPerson = new Person("Alice"); int index = people.indexOf(searchPerson); // Will be -1 because equals() not overridden System.out.println("Index found: " + index); } }
Output
Index found: -1
Quick Reference
Remember these points when using indexOf() with ArrayList:
| Method | Description |
|---|---|
| indexOf(element) | Returns index of first occurrence or -1 if not found |
| lastIndexOf(element) | Returns index of last occurrence or -1 if not found |
| contains(element) | Returns true if element exists in the list |
| equals() | Must be overridden in custom objects for correct indexOf behavior |
Key Takeaways
Use ArrayList's indexOf() method to find the first index of an element.
indexOf() returns -1 if the element is not present in the list.
For custom objects, override equals() to ensure indexOf() works correctly.
indexOf() only finds the first occurrence if duplicates exist.
Always check the returned index before using it to avoid errors.