Google+ How the size of ArrayList grows dynamically? ~ Java Geek Zone

Wednesday, 28 October 2015

On 07:01 by Unknown in , , , ,    2 comments
We all know in java ArrayList does not have limit unlike Array where we can only add fixed number of elements.

ArrayList allows dynamically adding and removing the elements in this list. So question comes HOW?

By default initial capacity of an array is defined with constant DEFAULT_CAPACITY

private static final int DEFAULT_CAPACITY = 10;


If we closely look at the add method in the source code of ArrayList.java. Click here to get whole file.

public boolean add(E e)
    
{
   
     ensureCapacity(size+1);
     elementData[size++] = e;         
     return true;
}



We can see in above code that before adding the element into the ArrayList its calling one method named “ensureCapacity”. This method makes sure what is the current size of the existing elements containing in the array and what is the maximum allowed size for the array at this point of time?

So if we are trying to add more element than its maximum allowed size then maximum allowed size needs to be increased in order to accommodate new elements.

But here we must notice that “elementData” is an array only and array does not grow dynamically.

private transient Object[] elementData; 


Here is the main thing to notice

Internally new array is created with new capacity and then elements from existing array are copied to the new array with bigger capacity.

elementData = Arrays.copyOf(elementData, newCapacity);

New capacity is calculated with below expression:

int newCapacity = (oldCapacity * 3)/2 + 1;


If you want to see this happening, You can try to execute the below code snippet in debug mode and monitor elementData array as shown in below figure.




package com.javageekzone.collection;

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample 
{
 public static void main(String[] args) 
 {
  List list = new ArrayList();

  for (int counter = 1; counter < 1000; counter++) 
  {
   list.add(counter);
  }
 }
}


































































I hope you now know how the size of ArrayList grows dynamically. Please let me know by comments if you still have any doubts.

Cheers!!!

2 comments:

  1. I have one doubt, as you said the initial capacity is 10 for ArrayList, let's say we have only 6 elements to fill, what will happen to the 4 unused spaces, compiler will delete the spaces or will keep them.

    ReplyDelete
    Replies
    1. To get those extra space released you need to use a method trimToSize() .

      Delete