The indexOf() method of the ArrayList class is used to find the index of the first occurrence of a specified element in the list. If the element appears multiple times, it returns the index of its first occurrence. If the element is not present, it returns -1.
- Returns the index of the first matching element.
- Returns -1 if the specified element is not found.
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
// Find the index of "Banana"
int index = fruits.indexOf("Banana");
System.out.println("Index of Banana: " + index);
}
}
Output
Index of Banana: 1
Explanation: In the above example, the indexOf() method searches for "Banana" and returns its index, which is 1.
Syntax
public int indexOf(Object o)
Parameter: o-> The element whose first occurrence is to be searched.
Return Value
- Returns the index of the first occurrence of the specified element.
- Returns -1 if the element is not found.
Example: Finding the First and Last Occurrence
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(20);
numbers.add(40);
// Find first and last occurrence
System.out.println("First occurrence of 20: "
+ numbers.indexOf(20));
System.out.println("Last occurrence of 20: "
+ numbers.lastIndexOf(20));
}
}
Output
First occurrence of 20: 1 Last occurrence of 20: 3
Explanation: The element 20 appears twice in the list. indexOf() returns the first occurrence (index 1), while lastIndexOf() returns the last occurrence (index 3).
Example: Searching for a Non-Existing Element
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> cities = new ArrayList<>();
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Chennai");
// Search for an element
int index = cities.indexOf("Pune");
System.out.println("Index of Pune: " + index);
}
}
Output
Index of Pune: -1
Explanation: Since "Pune" is not present in the ArrayList, the indexOf() method returns -1, indicating that the element was not found.
indexOf() Vs lastIndexOf()
| indexOf() | lastIndexOf() |
|---|---|
| Returns the first occurrence of an element. | Returns the last occurrence of an element. |
| Searches from the beginning of the list. | Searches from the end of the list. |
Returns -1 if the element is not found. | Returns -1 if the element is not found. |
Advantages of indexOf() Method
- Quickly locates an element in an ArrayList.
- Returns the first occurrence when duplicate elements exist.
- Returns -1 if the element is absent, making existence checks easy.
- Works with all object types, including custom objects (using equals()).
- Useful for searching, validation, and conditional processing.