I have a basic question on Java ArrayList
.
When ArrayList
is declared and initialized using the default constructor, memory space for 10 el
When we try to add an object to the arraylist,
Java checks to ensure that there is enough capacity in the existing array to hold the new object. If not, a new array of a greater size is created, the old array is copied to new array using Arrays.copyOf and the new array is assigned to the existing array.
Look at the code below (taken from Java ArrayList Code at GrepCode.com).
Edit:
public ArrayList() Constructs an empty list with an initial capacity of ten.
public ArrayList(int initialCapacity) we can specify initial capacity.
public ArrayList(Collection c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Now when we use ArrayList() constructore we get a ArrayList with Size=10 On adding 11th element in the list new Arraylist is created inside ensureCapacity() method.
Using following formula:
int newCapacity= (oldCapacity * 3)/2 +1;