Tuesday, November 6, 2012

IndexOutOfBoundsException in add Method of List Interface in Java

import java.util.*;
public class addError {
    public static void main(String[] args) {

    //Error (a)
    ArrayList a1 = new ArrayList();
    a1.add(0, "0");
    a1.add(1, "after 0 ");
    a1.add(2, "after 1 ");
    a1.add(4, "after 2 ");
    /*
       a1.add(4) ? what is this ?....
    */
       
    /*
       The above and below Array add method will show an IndexOutOfBoundsException because 
       in list (interface) the method's index should follow sequentially starting from 0 to n but in the 
       list above we have added the 4th index directly after 2nd index and hence the list adds upto 
       0,1,2 but after 2 when it is expecting the 3rd index to be entered in the memory storage... the 
       4th element is entered in memory and hence it throws IndexOutOfBoundsException as list 
       stores in memory only sequentially.
   
       Index should start from 0 and not from 1, the below add method shows error since the first 
       index should be 0 and following sequentially
    */
    //Error (b)
    a1.add(1, "1");
    a1.add(2, "after 1 ");
    a1.add(3, "after 2 ");
    a1.add(4, "after 3 ");
   
  }
}

Answer :
------------
/*
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:612)
    at java.util.ArrayList.add(ArrayList.java:426)
    at addError.main(addError.java:10)

    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:612)
    at java.util.ArrayList.add(ArrayList.java:426)
    at addError.main(addError.java:9)
*/

No comments:

Post a Comment