ArrayList IndexOutOfBoundsException despite adding within the capacity of the list

I have following code

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(1, 555);
}

and it is initialize with 10 elements but i am getting exception

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 ListTest.main(ListTest.java:9)

while below code working fine

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(0, 555);
}

Why can someone explain me ? and How to fix the issue i want to put item in 1th,2nd or 5th position in my code ?

Jon Skeet
people
quotationmark

it is initialize with 10 elements

No, it isn't. It's initialized with an internal buffer size of 10, but that's largely an implementation detail. The size of the list is still 0, as you can confirm by printing out list.size() before your add call.

It's important to differentiate between "amount of space in the buffer ready to accept more elements without copying" and "the size of the list". From the add documentation:

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

Here size() is 0, and 1 > 0, hence the exception.

You should always check the documentation before assuming that it's the framework (or compiler) that's wrong.

How to fix the issue i want to put item in 1th,2nd or 5th position in my code?

You either need to add enough elements first, e.g.

for (int i = 0; i < 10; i++) {
    list.add(null);
}
list.set(1, 555);
list.set(2, 500);
list.set(5, 200);

Note that these are set operations, not add - it's not clear whether you really want to insert or modify.

Or you should potentially use an array instead. For example:

int[] array = new int[10];
array[1] = 555;
array[2] = 500;
array[5] = 200;

In both cases, it's important to understand that indexes are 0-based - so list.set(1, 555) changes the second element of the list. You'd want list.set(0, 555) to change the first element. The same applies for arrays.

people

See more on this question at Stackoverflow