What is the use of public ArrayList(int initialCapacity) constructor if it does not save me from IndexOutOfBoundsException by returning null when I try to get an element of this list for an index which is smaller than initialCapacity?
Asked
Active
Viewed 105 times
0
-
You may be getting confused between the _size_ and _capacity_ of an ArrayList. The capacity is how many elements it can contain before it needs to resize its backing array; the size is how many elements it _does_ contain. Whatever initial capacity you give the list, its initial size is zero. – Andy Turner Sep 02 '21 at 20:25
1 Answers
1
An ArrayList
as its name suggests is backed by an array.
An array has a fixed size in Java.
When you add an item in an ArrayList
, if the underlying array size is not large enough to contain the new item then a new array is created with a larger size and data copied to it.
This process of creating new array and copying data is "costly" (relatively).
If you already know in advance how many items you will put in the list, specifying the initialCapacity
can improve performances as it will avoid some allocation/copy operations.

Gaël J
- 11,274
- 4
- 17
- 32