Alex Rivera | Logout

ArrayList out of bounds exception

Asked 2012-01-17T13:56:25.367
8

I have the following code:

ArrayList<Integer> arr = new ArrayList<Integer>(10);
arr.set(0,5);

I am getting an index out of bounds error, and I don't know why. I have declared the ArrayList of size 10. Why do I get this error?

Edit
Report

3 Answers

4

looking into JDK source code of ArrayList.set(int, E) gives a hint: you need to have at least N elements in your list before you can call set(N-1, E).

Add your elements via add() method.

answered 2012-01-17T13:59:30.210
0

set(int index, E element) Replaces the element at the specified position in this list with the specified element. U should use add()

answered 2012-01-17T14:00:39.813
0

In the constructor, you have specified an initial capacity. However, the size of the list is still 0 because you have not added any elements yet.

From the documentation of ArrayList.set():

IndexOutOfBoundsException - if index out of range (index < 0 || index >= size()).

answered 2012-01-17T14:01:42.953

Your Answer