ArrayList list = new ArrayList (20); The list in is expanded several times ()
A 0 B 1 C 2 D 3
Answer: A
dynamic expansion mechanism of ArrayList
Initialization: There are three different ways
The default constructor will initialize the internal array with the default size: public ArrayList ();
Constructs with a ICollection object and adds the elements of the collection to the Arraylist:public ArrayList (collection<? extends e> c)
Initializes an internal array with the specified size: public ArrayList (int initialcapacity)
Here we focus on the implementation process of the parameterless constructor:
The code has an initial capacity of 0. In the previous jdk1,6, the initial capacity was 10. conditions for expansion:
According to the minimum required capacity mincapacity to compare the capacity length of arrays, if mincapactity is greater than or equal to the array capacity, expansion is required. (If the actual storage array is an empty array, the minimum required capacity is the default capacity)
To achieve expansion:
In the JDK7, use the >> bitwise operation to move one position to the right. Capacity equivalent to 1.5 times times the expansion;
Example: Add 20 elements to ArrayList
10 (default) object space is assigned the first time an element is inserted. The expansion will then increase by 1.5 times times.
That is, when adding the 11th data, ArrayList continue to expand into 10*1.5=15;
When the 16th data is added, the continuous expansion becomes 15 * 1.5 = 22;
Summarize:
In JDK1.7, if the initial array capacity is 0, the capacity is really allocated when the real arrays are added.
In JKD1.6, the initial array capacity is 10 if it is constructed by means of an parameterless construct. The capacity is 1.5 times times plus 1 after each expansion through the copeof. The above is the principle of dynamic expansion.