What data structure does an ArrayList use internally?
ArrayList uses an Array of Object to store the data internally. When you initialize an ArrayList, an array of size 10 (default capacity) is created and an element added to the ArrayList is actually added to this array. 10 is the default size and it can be passed as a parameter while initializing the ArrayList.
ArrayList is a resizable array implementation in java. The backing data structure of ArrayList is an array of Object class. When creating an ArrayList you can provide initial capacity then the array is declared with the given capacity. The default capacity value is 10.
ArrayList uses an Object class array to store the objects. By default, ArrayList creates an array of size 10. While initializing the Array, we can specify the size of Array. When adding or removing elements, the space in the Array will automatically be adjusted.
The ArrayList size increases dynamically because whenever the ArrayList class requires to resize then it will create a new array of bigger size and copies all the elements from the old array to the new array.
Internally an ArrayList
uses an Object[]
.
As you add items to an ArrayList
, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.
Now, there is more room left, and the new element is added in the next empty space.
Since people really like the source code:
/** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. */ private transient Object[] elementData;
Straight out of the JDK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With