ArrayList and HashMap are a few of the most frequently used data structures in Java development. So I would like to talk about the importance of instantiating these classes with initial capacity. Let me explain how the ArrayList works internally, so that you get a good insight. HashMap works almost the same way an ArrayList works, so I haven’t covered the details of that separately. But all the tips given below are applicable for HashMap as well.
As the name implies, ArrayList is a list of array elements (i.e. Object[]). ArrayList has some good utility methods to increment array size and manipulate arrays easily.
Let us take the following example:
ArrayList sampleList = new ArrayList();
When the JVM executes this statement, it creates an array with size of 10 (default capacity) in the memory. As it creates just 10 elements, it doesn’t mean that you can add only 10 elements in this list; you can add more than 10 elements. When you add an11th element to this list, ArrayList internally extends its array size. It creates a new array with size of 20, and copies the old 10 elements to the new array and adds the 11th element to the array. So the old array with size 10 will be sending for garbage collection.
For this if we use the following code, the arraylist will create 11 arrays initially, so that when you add the 11th element, the array size need not be extended.
ArrayList sampleList = new ArrayList(11);
The advantages are:
-
We can improve the memory usage
-
We can improve the performance (i.e. additional time for creation of arrays can be saved)
Some of the tips that could be implemented in your project:
- Specify the initial capacity while instantiating ArrayList and HashMap
- If you don’t know the exact initial capacity, please perform an evaluation and come up with some approximate number.
- If you cannot even come-up with approx. initial capacity, then provide enough comments in the code that states the reason why initial capacity could not be provided in that case.
Leave a comment