1

As per the Java API the default capacity for a java.util.ArrayList is 10.

public ArrayList()

Constructs an empty list with an initial capacity of ten.

I created a list without specifying the initial capacity as below and found that the initial capacity is 0 for the list.

ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list50 = new ArrayList<String>(50);
list.add("1");
list50.add("2");
System.out.println(list.size());

List without initial capacity List with initial capacity specified

I know i am making some silly mistake in interpretation, please correct me.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ankit
  • 609
  • 2
  • 10
  • 26

2 Answers2

4

The initial capacity of a newly instantiated ArrayList is 0 - for performance reasons, an empty ArrayList uses a shared default array of size 0, so that if no new items are added to the list, you don't pay for allocating a new array that is never used.

Once the first item is added, the DEFAULT_CAPACITY (which is 10) is then used, i.e. the ArrayList creates a new array with size 10, which will then hold the first item (and has 9 additional, empty slots).

So I think you indeed used a slightly mistaken interpretation of the documentation.

The initial capacity is 0, and is then increased to 10 upon adding the first item, in order to avoid immediate reallocation for adding the next subsequent 9 items.

Markus Fischer
  • 1,326
  • 8
  • 13
  • ArrayList al = new ArrayList(); [Size: 0, Capacity: 0] ArrayList al = new ArrayList(5); [Size: 0, Capacity: 5] ArrayList al = new ArrayList(new ArrayList(5)); [Size: 0, Capacity: 0] al.add( "shailesh" ); [Size: 1, Capacity: 10] – Shailesh Vikram Singh Feb 13 '18 at 04:53
1

size and capacity are not the same... every time you call add, ArrayList invoke ensureCapacityInternal, there you can find DEFAULT_CAPACITY which is 10 as you pointed....

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

so this statement

minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);

increase the capacity to 10 after the 1st insertion

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97