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);
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With