Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java memory allocation in Arraylist

How does java handle getting new memory space when adding a new element in Arraylist? For example, there is no free space after the list.

Tx

like image 525
dinafication Avatar asked Sep 11 '26 19:09

dinafication


2 Answers

So when you add element in ArrayList internally it calls following method :

/**
     * Increases the capacity of this <tt>ArrayList</tt> instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     *
     * @param   minCapacity   the desired minimum capacity
     */
public void ensureCapacity(int minCapacity) {
    modCount++;
    int oldCapacity = elementData.length;
    if (minCapacity > oldCapacity) {
        Object oldData[] = elementData;
        int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
        newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
    }
    }

And in above method , Arrays.copyOf method further reaches to following native method ,

 public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

So for java you have to see openjdk native method code.

like image 121
Prateek Avatar answered Sep 13 '26 08:09

Prateek


Basically Java's ArrayList usually ensures enough space in an array for the elements to fit. If the array is not long enough then it provide more space for them: create new array with the double size of the original array and copies the elements into it. (DEFAULT_CAPACITY = 10)

public void ensureCapacity(int minCapacity){

 int current = data.length;

 if (minCapacity > current)
   {
     E[] newData = (E[]) new Object[Math.max(current * 2, minCapacity)];
     System.arraycopy(data, 0, newData, 0, size);
     data = newData;
   }
}

You can see it from the implementation ensureCapacity method of Arraylist:

http://developer.classpath.org/doc/java/util/ArrayList-source.html

If it can not provide enough space then it will throw an "java.lang.OutOfMemoryError: Java heap space"

You can check this here: http://javarevisited.blogspot.com/2011/09/javalangoutofmemoryerror-permgen-space.html

like image 36
Balazs Varhegyi Avatar answered Sep 13 '26 09:09

Balazs Varhegyi