Open In App
Related Articles

Java.util.Arraylist.indexOf() in Java

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax :
public int IndexOf(Object o)
obj : The element to search for.
// Java code to demonstrate the working of
// indexOf in ArrayList
  
// for ArrayList functions
import java.util.ArrayList;
  
public class IndexOfEx {
  public static void main(String[] args) {
       
  // creating an Empty Integer ArrayList
  ArrayList<Integer> arr = new ArrayList<Integer>(5);
  
  // using add() to initialize values
  arr.add(1);
  arr.add(2);
  arr.add(3);
  arr.add(4);
  
  // printing initial value
  System.out.print("The initial values in ArrayList are : ");
  for (Integer value : arr) {
  System.out.print(value);
  System.out.print(" ");
  }  
  
  // using indexOf() to find index of 3
  int pos =arr.indexOf(3);
    
  // prints 2
  System.out.println("\nThe element 3 is at index : " + pos);
  }
    
}   

                    
Output:
The initial values in ArrayList are : 1 2 3 4 
The element 3 is at index : 2

Practical Application : The index functions are mostly useful to determine last or first occurrence of events, for example last occurrence of 6 in a throw of a die, or 1st occurrence of any letter in a name etc. One more example:
// Java code to demonstrate the application of
// index functions in ArrayList
  
// for ArrayList functions
import java.util.ArrayList;
  
public class AppliIndex {
  public static void main(String[] args) {
       
  // creating an Empty Integer ArrayList
  ArrayList<Integer> arr = new ArrayList<Integer>(10);
  
  // using add() to initialize dice values
  arr.add(1);
  arr.add(2);
  arr.add(4);
  arr.add(6);
  arr.add(5);
  arr.add(2);
  arr.add(6);
  arr.add(1);
  arr.add(6);
  arr.add(4);
  
  // using IndexOf() to find first index of 6
  int pos1 =arr.indexOf(6);
    
  // using lastIndexOf() to find last index of 6
  int pos2 =arr.lastIndexOf(6);
    
  // to balance 0 based indexing
  pos1 = pos1+1;
  pos2 = pos2+1;
    
  // printing first index of 6
  System.out.println("The first occurrence of 6 is  : " + pos1);
    
  // printing last index of 6
  System.out.println("The last occurrence of 6 is  : " + pos2);
    
  }
    
}   

                    
Output:
The first occurrence of 6 is  : 4
The last occurrence of 6 is  : 9


Last Updated : 10 Oct, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads