简体   繁体   中英

ArrayList out of bounds exception

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?

You declared an ArrayList , that has the initial capacity of 10 elements, but you did not add an element to this list, ie the list is empty. set will replace an existing element, but since there is no element in the list, the exception is thrown. You have to add elements before, using the add method.

Initial capacity means that the array that the list maintains internally is of size 10 at the beginning. While adding more elements to the list, the size of this internal array might change.

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.

The initial array contained is specified as "10" the actual number of items in the array is 0.

To add "5" at the first index, just do arr.add(5)

The value passed to the ArrayList constructor is the initial capacity of the backing store of the array. When you add elements to a point that exceeds this capacity, internally the ArrayList will allocate a new storage array of a size and copy the items to the new backing store array.

From the documentation :

Constructs an empty list with the specified initial capacity.

(emphasis mine)

What you passed in the constructor is just the initial capacity of the array by which the list is backed. The list is still empty after construction. Moreover you should consider using a generic list if you want to store ie just Integers..

You have initialized arraylist with number of items 0 which means you just have 1 element in this array. and later you adding two numbers in this array.

Use arr.add(0.5) . set method will replace the existing element.

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

If you look at the javadoc note that it says:

Replaces the element at the specified position in this list with the specified element.

You need an element before you can replace one. Try

arr.add(5);

to just add an element.

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()).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM