Thursday, October 2, 2008

ArrayIndexOutOfBoundsException in Java



package com.index;

import java.util.ArrayList;
import java.util.List;

public class ListIndexTest {

 /**
  * @param args
  */
 public static void main(String[] args) {

  List<String> list = new ArrayList<String>();
  int indexOf = 0;
  try {
   indexOf = list.indexOf("test");
   System.out.println(list.remove(indexOf));
  } catch (ArrayIndexOutOfBoundsException e) {
   e.printStackTrace();
  }
  try {
   // avoiding exception by condition check.
   indexOf = list.indexOf("test");
   if(indexOf >= 0){
    System.out.println(indexOf + " "+ list.remove(indexOf));
   }else{
    System.out.println("index of test : "+indexOf);
   }
  } catch (ArrayIndexOutOfBoundsException e) {
   e.printStackTrace();
  }
  list.add("test");
  list.add("rest");
  list.add("quest");
  list.add("test");
  indexOf = list.indexOf("test");
  System.out.println(indexOf + " "+ list.remove(indexOf));
  indexOf = list.indexOf("test");
  if(indexOf >= 0){
   System.out.println(indexOf + " "+ list.remove(indexOf));
  }
 }

}


output:

java.lang.ArrayIndexOutOfBoundsException: -1
 at java.util.ArrayList.elementData(ArrayList.java:371)
 at java.util.ArrayList.remove(ArrayList.java:448)
 at com.index.ListIndexTest.main(ListIndexTest.java:17)
index of test : -1
0 test

2 test

No comments: