Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the default capacity of ArrayList 10?

I saw the java doc for ArrayList and found that the initial capacity of ArrayList is 10.

 /**  * Constructs an empty list with an initial capacity of ten.  */ public ArrayList() { this(10); } 

I think it would make sense if it were any power of 2, but why 10?

I also checked HashMap's initial capacity, and it's 16 which makes sense.

/**  * The default initial capacity - MUST be a power of two.  */ static final int DEFAULT_INITIAL_CAPACITY = 16;  /**  * Constructs an empty <tt>HashMap</tt> with the default initial capacity  * (16) and the default load factor (0.75).  */ public HashMap() {     this.loadFactor = DEFAULT_LOAD_FACTOR;     threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);     table = new Entry[DEFAULT_INITIAL_CAPACITY];     init(); } 

Is there any specify reason behind the number 10?

like image 347
Priyank Doshi Avatar asked May 29 '12 07:05

Priyank Doshi


People also ask

What is the default capacity of ArrayList?

The capacity property in ArrayList class gets or sets the number of elements that the ArrayList can contain. The default capacity is 4. If 5 elements are there, then its capacity is doubled and would be 8.

What is the default size of ArrayList in java 8?

ArrayList default size in JAVA 8 is stil 10. The only change made in JAVA 8 is that if a coder adds elements less than 10 then the remaining arraylist blank places are not specified to null.

What is the default capacity of ArrayList and Hashtable?

I know that the default capacity of Vector class in java is 10 and similarly ArrayList also have it's default capacity 10.

How does ArrayList increase capacity?

The java. util. ArrayList. ensureCapacity(int minCapacity) method increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.


1 Answers

The ArrayList is simple growing array. When trying to add element, and the buffer size is exceeded, it is simply growing. So the initial size can be any positive value.

The 1 would be too little. Even with a few elements we will have a few resize operations.

The 100 would be a loss of space.

So, the 10 is compromise. Why 10 and not 12 or 8? First hint, that the typical use cases were analysed and this is the best fit between lost of performance and lost of space. However, I think, seeing the Sun's original code, that it wasn't analysed so deeply and it is an arbitrary 'not too small, not too big' number.

like image 194
Stepan Vihor Avatar answered Sep 22 '22 06:09

Stepan Vihor