ArrayList arguably would be the most used collection along with the HashMap. Many of us programmers whip up code everyday which contains atleast one of these data structures to hold objects. I have already discussed how HashMap works internally in Java, in this post I'll try to explain how ArrayList internally works in Java.
As most of us would already be knowing that ArrayList is a Resizable-array implementation of the List interface i.e. ArrayList grows dynamically as the elements are added to it. So let's try to get clear idea about the following points-
- How ArrayList is internally implemented in Java.
- What is the backing data structure for an ArrayList.
- How it grows dynamically and ensures that there is always room to add elements.
Note - Code of ArrayList used here for reference is from Java 10.
Where does ArrayList internally store elements
Basic data structure used by Java ArrayList to store objects is an array of Object class, which is defined as follows-
transient Object[] elementData;
I am sure many of you would be thinking why
transient and how about
serializing an ArrayList then?
ArrayList provides its own version of readObject and writeObject methods so no problem in serializing an ArrayList
and that is the reason, I think, of making this Object array as transient.