indexOf(Object o) method of List Interface in java

indexOf(Object o) method of List Interface in java


Posted in : Core Java Posted on : January 7, 2011 at 6:29 PM Comments : [ 0 ]

In the following example we will show you the method of finding Index of an element in a list using indexOf(Object o) method of List interface in java.

indexOf(Object o) method of List Interface in java

In the following example we will show you the method of finding Index of an element in a list using indexOf(Object o) method of List interface in java.

Syntax

public int indexOf(Object o)

This method returns an index value of an element of a list.

In this method you can find an index value of an element from a list. It returns an integer value of an element in terms of index position of the first occurrence of that specified element or returns (-1) if the specified element does not exist in the list.

Parameter Description

Object o : It takes an argument as an element which is to be searched from list, and returns an integer value of that element as it's index value.

Example of indexOf(Object o) method 

In this example we will show you how does indexOf(Object o) method works in List interface. This example will help you to understand how can you find an index value of first occurrence of an element from the list. Through this example we will show you adding of element to the list, get the element of list with their position value, and index of the specified element. 

Example:-


package Devmanuals.com;
import java.util.ArrayList;
public class ListIndexOf {
public static void main(String[] args) {
int in;
ArrayList al = new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("D");
al.add("F");
System.out.println("Elements of list are :" +al);
System.out.println("size of list = "+al.size());
for(int i=0;i<al.size();i++)
System.out.println("Position of element " +al.get(i) + " is = " +i );
//here method returns Index value
in=al.indexOf("D");
System.out.println("Index of first occurrence of element D = "+in);
//here method returns -1 because G is not in list
in = al.indexOf("G");
System.out.println("Index Of element G = "+in);
}
}

Output :

Elements of list are :[A, B, C, D, D, F]

size of list = 6

Position of element A is = 0

Position of element B is = 1

Position of element C is = 2

Position of element D is = 3

Position of element D is = 4

Position of element F is = 5

Index Of element D = 3

Index Of element G = -1 (return (-1) because 'G' does not exist in above list)

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics