Java.util.ArrayList.indexOf() Method

Advertisements


Description

The java.util.ArrayList.indexOf(Object) method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Declaration

Following is the declaration for java.util.ArrayList.indexOf() method

public int indexOf(Object o)

Parameters

  • o -- The element to search for.

Return Value

This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Exception

  • NA

Example

The following example shows the usage of java.util.ArrayList.indexOf() method.

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    ArrayList<String> arrlist = new ArrayList<String>(5);

    // use add() method to add values in the list
    arrlist.add("G");
    arrlist.add("E");
    arrlist.add("F");
    arrlist.add("M");
	
    System.out.println("Size of list: " + arrlist.size());

    // let us print all the values available in list
    for (String value : arrlist) {
      System.out.println("Value = " + value);
    }  

    // retrieving the index of element "E"
    int retval=arrlist.IndexOf("E");
    System.out.println("The element E is at index " + retval);
  }
}   

Let us compile and run the above program, this will produce the following result:

Size of list: 4
Value = G
Value = E
Value = F
Value = M
The element E is at index 1



Advertisements
Advertisements