Java.util.Arraylist.indexOf() in Java
Last Updated :
10 Oct, 2019
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.
import java.util.ArrayList;
public class IndexOfEx {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>( 5 );
arr.add( 1 );
arr.add( 2 );
arr.add( 3 );
arr.add( 4 );
System.out.print( "The initial values in ArrayList are : " );
for (Integer value : arr) {
System.out.print(value);
System.out.print( " " );
}
int pos =arr.indexOf( 3 );
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:
import java.util.ArrayList;
public class AppliIndex {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>( 10 );
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 );
int pos1 =arr.indexOf( 6 );
int pos2 =arr.lastIndexOf( 6 );
pos1 = pos1+ 1 ;
pos2 = pos2+ 1 ;
System.out.println( "The first occurrence of 6 is : " + pos1);
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...