Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList IndexOutOfBoundsException despite giving an initial capacity

When I do

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

Java gives me

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0     at java.util.ArrayList.rangeCheck(Unknown Source)     at java.util.ArrayList.set(Unknown Source)     at HelloWorld.main(HelloWorld.java:13) 

Is there an easy way I can pre-reserve the size of ArrayList and then use the indices immediately, just like arrays?

like image 920
CuriousMind Avatar asked Jun 25 '13 15:06

CuriousMind


People also ask

How do you set initial capacity of an ArrayList?

When you create an ArrayList you can specify the initial capacity. For example: ArrayList<Integer> arrayList = new ArrayList<>(100); In this case, the initial capacity of the ArrayList will be 100.

What is the initial capacity of the ArrayList list in Java?

Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold.

How is the current capacity of an ArrayList increased in Java when initial size is full?

The grow method in the ArrayList class gives the new size array. In Java 8 and later The new capacity is calculated which is 50% more than the old capacity and the array is increased by that capacity.


1 Answers

How about this:

ArrayList<Integer> arr = new ArrayList<Integer>(Collections.nCopies(10, 0)); 

This will initialize arr with 10 zero's. Then you can feel free to use the indexes immediately.

like image 186
jh314 Avatar answered Sep 22 '22 17:09

jh314