How does an ArrayList expand itself when its maximum capacity is reached in java?

By | March 5, 2023

In Java, when an ArrayList reaches its maximum capacity, it automatically expands itself by creating a new array with a larger capacity and copying the elements from the old array to the new array.

The new capacity is calculated based on a growth factor, which is typically 1.5. This means that the new capacity will be 1.5 times the current capacity. For example, if the current capacity is 10 and the growth factor is 1.5, then the new capacity will be 15.

When the ArrayList is expanded, it creates a new array of the new capacity, and then copies the existing elements from the old array to the new array. This copying process can be expensive, especially if the ArrayList contains a large number of elements, so it is important to choose an appropriate initial capacity to minimize the number of times the ArrayList needs to be expanded.

To set an initial capacity for an ArrayList, you can use the constructor that takes an integer argument, like this:

ArrayList<String> myList = new ArrayList<String>(10);

This creates an ArrayList with an initial capacity of 10. If you know the approximate size of the ArrayList beforehand, it is a good idea to set the initial capacity to that size to minimize the number of expansions that need to occur.

You may also like:

What is difference between Iterator and LisIterator?
Is there concurrent version for TreeMap and TreeSet in Java Collections Framework?
Why Prime Numbers are considered in writing certain algorithms like hashcode()?

Leave a Reply

Your email address will not be published. Required fields are marked *