Detailed explanation of Java ArrayList capacity expansion examples
This paper mainly studies the relevant contents of the detailed explanation of the example of Java ArrayList expansion. The details are as follows.
First of all, we need to know that the essence of ArrayList is an array of object type. The expansion of ArrayList is actually the expansion of this array of object type.
1、 Capacity allocation of ArrayList when created
There are three ways to create an ArrayList
1. Default size creation (default is 0)
After creation, the capacity of Al is 0. You can know from the following code.
2. Specify size to create
Create an ArrayList object with a capacity of 5, which is actually an object array with a length of 5. You can know from the following code.
3. Specify element collection creation
The ArrayList object is created above and initialized with a list of [1,5]. In fact, an object array with a length of 5 is created, and the contents of the array are [1,5]. You can know from the following code.
2、 The capacity of ArrayList expands when inserting elements
The above process is as follows:
1. Create an ArrayList with size 5 and content [1,5]. -- The initial capacity is 5
2. Add the collection {6,10} to the ArrayList object- At this time, the capacity of the ArrayList object needs to be expanded.
View source code:
The above process can be summarized as follows:
1. The original size of ArrayList + the size of the set to be inserted numnew = the minimum length mincapacity of the expanded ArrayList
2. If the original size of ArrayList is 0, that is, ArrayList is empty, the minimum length of ArrayList after expansion mincapacity = math Max (10, mincapacity), that is, the minimum length mincapacity after expansion, is not just the original length size plus the length of the inserted set numnew.
3. The minimum length mincapacity after expansion obtained above is not the final length after expansion and needs further calculation.
(1) Get the original size oldcapacity of ArrayList (2) get the new expanded size: newcapacity = oldcapacity * 1.5; (3) compare the expanded minimum length mincapacity calculated above with the expanded size newcapacity obtained here, and take the larger one as the final expanded size.