Tuesday, February 8, 2011

Why ArrayList's Default size is 10?

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 10 elements behind the scenes. Ofcourse those 10 elements are all null.

Every time the array is full, ArrayList creates a new, larger array and copies the elements from the old array to the new array. You don't want that to happen every time that you add an element to the ArrayList (copying the array takes time, especially if the array is large), so ArrayList does it in steps of 10 or so.

If you want to know exactly how it works, look for the file src.zip in your JDK installation directory. Open it and lookup the source code for java.util.ArrayList in there.

Regards javaranch.com


If you could click on some of the google ads you see on the right side. It will help me to run this blog and motivates me ;)

4 comments: