Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting IndexOutOfBoundException

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);
}
like image 624
nIx.. Avatar asked Jan 28 '26 18:01

nIx..


2 Answers

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.

like image 179
Elliott Frisch Avatar answered Jan 31 '26 08:01

Elliott Frisch


Here's the problem:

list.add(1, 2);

To fix it, do this:

list.add(0, 2);

Or even simpler, this:

list.add(2);

Remember: in Java, lists an arrays start at index 0, you'll get an error if you try to add an element at index 1 in an empty list.

like image 29
Óscar López Avatar answered Jan 31 '26 07:01

Óscar López