Friday 21 February 2020

Java: List Capacity vs Size

‘size’ specifies number of elements in the list, whereas capacity specifies how many elements the list can accommodate more.

For example,
List<Integer> list = new ArrayList<> (10);

Above statement defines an ArrayList of capacity 10 and size 0.

Let’s add one element to ArrayList.
list.add(23);

When you add one element to the list, size becomes 1 and capacity becomes 10.


What if you are inserting more elements greater than list capacity?
A new Array with more capacity is created to allocate more elements. All the existing elements of list are copied to new array (List is backed by an array).

You may like

No comments:

Post a Comment