The indexOf() method of java.util.AbstractList class is used to return the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
Syntax:
public int indexOf(Object o)
Parameters: This method takes Object o as parameter which is 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.
Below are the examples to illustrate the indexOf() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
AbstractList<Integer>
arrlist1 = new ArrayList<Integer>();
arrlist1.add( 10 );
arrlist1.add( 20 );
arrlist1.add( 30 );
arrlist1.add( 40 );
arrlist1.add( 50 );
System.out.println( "ArrayListlist : "
+ arrlist1);
int index = arrlist1.indexOf( 30 );
System.out.println( "index : " + index);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
ArrayListlist : [10, 20, 30, 40, 50]
index : 2
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
AbstractList<Integer>
arrlist1 = new ArrayList<Integer>();
arrlist1.add( 10 );
arrlist1.add( 20 );
arrlist1.add( 30 );
arrlist1.add( 40 );
arrlist1.add( 50 );
System.out.println( "ArrayListlist : "
+ arrlist1);
int index = arrlist1.indexOf( 25 );
System.out.println( "Index of 25 : "
+ index);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
ArrayListlist : [10, 20, 30, 40, 50]
Index of 25 : -1
Example 3: For Null value
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
AbstractList<Integer>
arrlist1 = new ArrayList<Integer>();
arrlist1.add( 10 );
arrlist1.add( 20 );
arrlist1.add( 30 );
arrlist1.add( 40 );
arrlist1.add( 50 );
System.out.println( "ArrayListlist : "
+ arrlist1);
Object value = null ;
int index = arrlist1.indexOf(value);
System.out.println( "Index of null : "
+ index);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
ArrayListlist : [10, 20, 30, 40, 50]
Index of null : -1