Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ArrayList work?

Tags:

java

arraylist

What data structure does an ArrayList use internally?

like image 282
AutoMEta Avatar asked Aug 12 '10 13:08

AutoMEta


People also ask

What is ArrayList How does it work?

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.

What is ArrayList and how it works internally?

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.

How is ArrayList implemented in Java?

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.

How does ArrayList grow dynamically?

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.


1 Answers

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.

like image 193
jjnguy Avatar answered Oct 05 '22 18:10

jjnguy