Use a multiple-choice question as the beginning of this article!
ArrayList list = new ArrayList(20); several times are the list expanded in ArrayList(20);
A.0
B.1
C.2
D.3
Answer: A
1. The default initial capacity of ArrayList is 10. Of course, you can also customize the initial capacity. As elements are added dynamically, its capacity may increase dynamically. Then the formula for expansion is:
New Capacity = Old Capacity/2 + Old Capacity
For example: the initial capacity is 4, and the new capacity after each expansion of its capacity is: 4->6->9->13->19->…
That is, each time it expands to 1.5 times the original foundation
There are three constructors of ArrayList:
(1) ArrayList() constructs an empty list with an initial capacity of 10.
(2) ArrayList(Collection<? extends E> c) Constructs a list of elements containing the specified collection, which are arranged in the order in which the collection's iterator returns them.
(3) ArrayList(int initialCapacity) constructs an empty list with a specified initial capacity.
The third constructor is called, which is directly initialized to a list of size 20, and has no expansion, so choose A
If initialized to ArrayList(0), it will increase to 1 after the new capacity is calculated;
Similar to this,
2. The initial size of HashMap is 16. When it grows, the direct capacity doubles, such as the source code.
void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * );//Original capacity 2 times hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, ); } createEntry(hash, key, value, bucketIndex); }
3. The initial size of Vector is 10. If the size of each growth is not specified, the default is to double the growth.
Summarize
The above is all the content of this article about the analysis of the automatic expansion mechanism of ArrayList, and I hope it will be helpful to everyone. Interested friends can continue to refer to this site:Detailed explanation of Spring Java-based container configuration、Introduction to the method of removing elements using remove method in a for loopWait, if you have any questions, you can leave a message at any time. The editor will reply to everyone in time. Thank you for your support for this site!