Translate the content to your language. Select your Language below.

Sunday, April 26, 2015

How ArrayList works in Collection?

ArrayList obj = new ArrayList();
obj.add("xxxxxxxx");

When add method is called, internally a method called ensureCapacity will be called. The method looks as like below.

ensureCapacity(size + 1);  [Here size means array object's current size]

An array object defaults size is 10. If it is with in the size, results True and the element will be added to the ArrayList. If it is False, another method ResizeArray will be invoked from ExtendedSystem class. It looks like as below.

ExtendedSystem.resizeArray(newCapacity, elementData, 0, size);

newCapacity = (oldCapacity * 3)/2 + 1
elementData = the array instance copying the values
size = current length of the array

When it tries to get or retrieve an object by index in an array, a method called RangeCheck(index) will be called. If the index is available with in the array, it pulls the respective data.  If the index is out of scope, results IndexOutOfBounds exception.

Removing elements from the ArrayList uses System.arrayCopy(xxx) method for deletion.

System.arraycopy(src,srcposition,dest,destposition,length);

src – the source array.
srcposition – index from where to copy the values from source.
dest – the destination array.
destposition - index from where to copy the values to dest.
length – number of elements to copy from source to dest.