3

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

asked Aug 30, 2013 at 14:21
3
  • 2
    why not look at the sourcecode!? Commented Aug 30, 2013 at 14:22
  • These are JVM native calls. It's not implemented in Java. Commented Aug 30, 2013 at 14:22
  • 3
    Since when is ArrayList "not implemented in Java" ? Commented Aug 30, 2013 at 15:46

2 Answers 2

2

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.

answered Aug 30, 2013 at 14:34
1

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

answered Aug 30, 2013 at 14:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.