Friday 4 April 2014

Get the First Occurrence of the Element

int indexOf(Object o)
   Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

import java.util.*;

class ListIndexOf{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
    
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.println("Index Of 30 is " + myList.indexOf(30));
  System.out.println("Index Of 100 is " + myList.indexOf(100));
 } 
}

Output

Elements in myList are
[10, 20, 30, 40]
Index Of 30 is 2
Index Of 100 is -1

1. throws ClassCastException if the type of the specified element is incompatible with this list

2. throws NullPointerException if the specified element is null and this
list does not permit null elements




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment