How ArrayList works internally

Question: How ArrayList works internally?
Answer:
ArrayList is like an array which can grow in memory dynamically. And we also know that ArrayList is not synchronized by default. In this post we will see how ArrayList works internally.
ArrayList<String> al = new ArrayList<String>();

This is how we declare an ArrayList. Here we did not specify any size for the list. Since we have not specified any value for the ArrayList, the default size is "10". Internally ArrayList uses Object[] array. The object array list looks like this:
 private transient java.lang.Object[] elementData;
 
When ArrayList is created the below piece of code gets executed.

this.elementData = new Object[initialCapacity];

We add items to an ArrayList using .add(); function. As we add items to ArrayList, the list checks the maximum size and if there is any space available then new element will be added. If there is no space left then then a new array would be created with 50% more space than the current ArrayList and all the data would be copied to the newly created array.

No comments:

Post a Comment