Java Arraylist indexOf() Method (original) (raw)

Last Updated : 10 Dec, 2024

The indexOf() method in Java is used to find the index of the first occurrence of a specified element in an ArrayList.

**Example 1: Here, we will use the indexOf() method **to find the index of a specific element in an ArrayList.

Java `

// Java program to demonstrate the // use of indexOf() method import java.util.ArrayList;

public class GFG { public static void main(String[] args) {

    // Creating an ArrayList of Integers
    ArrayList<Integer> arr = new ArrayList<Integer>(5);

    // Adding elements to the ArrayList
    arr.add(1);
    arr.add(2);
    arr.add(3);

    // Printing the initial values 
    // in the ArrayList
    System.out.print("");
    for (Integer v : arr) {
        System.out.print(v + " ");
    }  

    // Using indexOf() to 
    // find the index of 3
    int p = arr.indexOf(3);

    // Prints the index of the element
    System.out.println("\nThe element 3 is at index: " + p);
}

}

`

Output

1 2 3 The element 3 is at index: 2

Syntax of ArrayList.indexOf() Method

public int indexOf(Object o)

**Example 2: Here, we use the indexOf() method **to find the first occurrence and lastIndexOf() **to find the last occurrence of a specific element.

Java `

// Java program to demonstrate the use of // indexOf() and lastIndexOf() methods import java.util.ArrayList;

public class GFG { public static void main(String[] args) {

    // Creating an ArrayList of Integers
    ArrayList<Integer> arr = new ArrayList<Integer>(6);

    // Adding elements to the ArrayList
    arr.add(1);
    arr.add(2);
    arr.add(4);
    arr.add(6);
    arr.add(5);
    arr.add(2);

    // Using indexOf() to find the 
    // first index of 4
    int p1 = arr.indexOf(4);
    
    // Using lastIndexOf() to find the 
    // last index of 4
    int p2 = arr.lastIndexOf(4);
    
    // Balancing the 0-based indexing
    p1 = p1 + 1;
    p2 = p2 + 1;
    
    // Printing first and last index of 4
    System.out.println("The first occurrence of 4 is: " + p1);
    System.out.println("The last occurrence of 4 is: " + p2);
}

}

`

Output

The first occurrence of 4 is: 3 The last occurrence of 4 is: 3

**Example 3: **If the specified element is not found in the ArrayList, the **indexOf() method will return -1.

Java `

// Java program to demonstrate the use of // indexOf() method with a non-existent element import java.util.ArrayList;

public class GFG { public static void main(String[] args) {

    // Creating an ArrayList of Integers
    ArrayList<Integer> arr = new ArrayList<Integer>(5);

    // Adding elements to the ArrayList
    arr.add(10);
    arr.add(20);
    arr.add(30);

    // Trying to find the index of 
    // a non-existent element
    int p = arr.indexOf(50);

    System.out.println("The index of 50 is: " + p);
}

}

`

Output

The index of 50 is: -1