VOOZH about

URL: https://www.geeksforgeeks.org/java/java-util-arraylist-indexof-java/

⇱ Java Arraylist indexOf() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Arraylist indexOf() Method

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.


Output
1 2 3 
The element 3 is at index: 2

Syntax of ArrayList.indexOf() Method

public int indexOf(Object o)

  • Parameter: The object o whose index is to find.
  • Return Type: An integer that represents the index of the first occurrence of the specified element in the list, or -1 if the element is not found.

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


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.


Output
The index of 50 is: -1


Comment