ArrayList exception outside of exception

I have the following code:

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

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

+4
source share
9 answers

You declared an ArrayList , which has an initial capacity of 10 elements, but you have not added an element to this list, i.e. the list is empty. set will replace an existing element, but since there is no element in the list, an exception is thrown. You must add elements earlier using the add method.

Initial capacity means that the array that stores the list inside has a size of 10 at the beginning. As more items are added to the list, the size of this internal array may change.

+7
source

The original array is specified as "10", the actual number of elements in the array is 0.

To add β€œ5” to the first index, just do arr.add (5)

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

+3
source

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

Add your items using the add() method.

+3
source

From the documentation :

Creates an empty list with the specified initial capacity.

(my emphasis)

+2
source

What you passed in the constructor is just the initial capacity of the array by which this list is supported. After construction, the list remains empty. In addition, you should consider using a generic list if you want to keep ie only integers.

+1
source

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

0
source

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

0
source

If you look at javadoc , pay attention:

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

You need an item before you can replace it. Try

 arr.add(5); 

just add an item.

0
source

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

From the documentation of ArrayList.set() :

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

0
source

Source: https://habr.com/ru/post/1391455/


All Articles