How does the add() function of ArrayList work?

Tram Ho

image.png

When coding with Java/Kotlin, we often have to manipulate the subclasses of List, typically ArrayList. It’s so common that we sometimes forget about the array data type (Array) – A data structure that dictates that elements must have the same type and fixed size and cannot be changed.

So why can ArrayList add/remove elements so conveniently? Let’s find out together.

Jumping into the Java source code, it’s easy to see that ArrayList is just a ‘sticky wrapper’ =)) Inside it uses an object array to store data: transient Object[] elementData; // non-private to simplify nested class access And also because Object is the largest data type in Java (People often call it Father Of Big – Father of to), List allows us to have generics to hold the data type whether any.

There are a few concepts that need clarification before getting started:

  • Capacity: The capacity of the array is the maximum number of elements that the elementData array can hold.
  • Length: The actual number of elements added to the array. And so length <= capacity.

Now we will go through the operation steps of add() function:

It’s really simple, just make sure the elementData array has enough space and then insert the new element at the end of the array.

However, we will learn the function ensureCapacityInternal(), this is the function that ensures the request for more space to be able to accommodate the newly added element. By default, the array will be initialized with enough space to hold 10 elements , if the space is exhausted, the grow() function will be called.

The grow() function is in charge of 2 things:

  1. Increase the size of the elementData array.

Next, copyOf() will call System.arraycopy() to copy the elements from the original array from the starting position of 0 to the copy array with the number of newLength = newCapacity calculated in the previous step.

Here we see that System.arraycopy is a native method written in C++, which copies the elements of the source array src to the destination array dest System.arraycopy() is used a lot, so it is optimized. memory and make it available through the Bionic Libc memmove() function. If the platform is available it will be used, otherwise Dalvik_java_lang_System_arraycopy will be used instead.


It turns out that the things that we have often used for a long time have been built extremely complex and elaborate, abstract under many layers but have to dig deep and learn very carefully to understand.

 

Share the news now

Source : Viblo