Saturday 17 February 2018

Does ArrayList in Java have default size?

Surprised ? Many developers might not aware of the fact that arraylist have some default size. Normally we consider arraylist with "0" size. Lets have a dig at the concept : 
ArrayList uses an array to store the elements. Arrays have a fixed size. The array that ArrayList uses has to have a default size, obviously. 10 is probably a more or less arbitrary number for the default number of elements. When you create a new ArrayList with nothing in it, then ArrayList will have made an array of 0 element, and when you add first element then it create array of 10 elements behind the scenes. Ofcourse those 9 elements are all null.
Using This line ...! 
List list=new ArrayList<String>();
Made an array of 0 element
list.add("FirstValue");
It create array of 10 elements behind the scenes with "FirstValue" at its 0 index.
Every time the array is full, ArrayList creates a new, larger array and copies the elements from the old array to the new array.

Note :- (copying the array time so better to think about its first)
if list.size == 9 and we do list.add("EleventhString")

It will create new array and copy all the data in newly created array.
The size of new arary depends on the current size of array and the algorithm is 
(CurrentSize of Array * 3/2) + 1

No comments:

Post a Comment

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...