Show Stopper Show Stopper - 1 month ago 13
Java Question

Set Method of ArrayList throwing IndexOutOfBoundsException

While working on

ArrayList
, I found after setting the initial size of array using the constructor with
initialCapacity
, then use
set()
will throw an exception although the array is created, but size isn't set correctly.

Using
ensureCapacity()
won't work either because it is based on the
elementData
array instead of
size
.

There are other side effects because of the static
DEFAULT_CAPACITY
with
ensureCapacity()
.

The only way to make this work is to use add() as many time as required after using the constructor.

Please check the code below.

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {

List test = new ArrayList(10);
test.set(5, "test");
System.out.println(test.size());
}


I am not sure why java is throwing this exception.

Behaviour I expected:
test.size()
should return 10 and set(5, ...) should work.

ACTUAL: throws an Exception
IndexOutOfBoundsException
.

So is it set method that is causing problem ?

Answer

test.set(5, "test"); is the statement that throws this exception, since your ArrayList is empty (size() would return 0 if you got to that statement), and you can't set the i'th element if it doesn't already contain a value. You must add at least 6 elements to your ArrayList in order for test.set(5, "test"); to be valid.

new ArrayList(10) doesn't create an ArrayList whose size is 10. It creates an empty ArrayList whose initial capacity is 10.