Getting IndexOutOfBoundException

Tags: ,



why does following main method gives IndexOutOfBoundException at list.add(1, 2)?

public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(1, 2);
    int total = list.get(0);
    System.out.println(total);
}

Answer

You can’t add an element at index 1 when it the ArrayList is empty. It starts at 0, or just use add.

public static void main(String[] args) {
  List<Integer> list = new ArrayList<Integer>();
  list.add(1);
  list.add(2);
  int total = list.get(0); // <-- You even use 0 here!
  System.out.println(total);
}

Per the ArrayList#add(int index, E element) javadoc,

Throws:

  IndexOutOfBoundsException - if the index is out of range 
  (index < 0 || index > size())

When size == 0, the index 1 is out of range.



Source: stackoverflow