当前位置:网站首页>Capacity expansion mechanism of ArrayList
Capacity expansion mechanism of ArrayList
2022-07-02 21:28:00 【java. lang.utils】
ArrayList Capacity expansion mechanism of
1, When the nonparametric construction method was just started
/** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {
};
/** * Constructs an empty list with an initial capacity of ten. */
// The first construction method
public ArrayList() {
// This actually points to an empty array
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/** * Shared empty array instance used for empty instances. */
private static final Object[] EMPTY_ELEMENTDATA = {
};
// The second construction method Construction method with parameters
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
// Complete the construction of the array
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
// If it is equal to 0 Point to an empty array
this.elementData = EMPTY_ELEMENTDATA;
} else {
// If it's a negative number Throw an exception
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/** * The third construction method * Convert the incoming collection into an array , And then through Arrays.copyOf Method to copy the elements in the set * Beidao elementData in . Again , If the length of the incoming set is 0, return * EMPTY_ELEMENTDATA */
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
2, Add method
/** * The size of the ArrayList (the number of elements it contains). * * @serial */
private int size;
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */
// Currently not thread safe
public boolean add(E e) {
// Before adding elements , A capacity expansion process will be performed , Judge whether to expand capacity
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
3, Came to ensureCapacityInternal How to look closely
private void ensureCapacityInternal(int minCapacity) {
// Judge whether it is equal to null , At this time elementData Meet the conditions , because elementData
// It's empty ,Math.max Take the maximum DEFAULT_CAPACITY = 10
// and minCapacity = 1 All final returns 10
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
// So now minCapacity be equal to 10
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
4, Chase down ensureExplicitCapacity Method
private void ensureExplicitCapacity(int minCapacity) {
modCount++; // The number of modifications is increased
// overflow-conscious code
// 10 - 0 > 0 true
if (minCapacity - elementData.length > 0) // Meet the conditions
grow(minCapacity);// Call the capacity expansion method
}
5, The last step grow Method
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */
private void grow(int minCapacity) {
// overflow-conscious code
// oldCapacity = 0, because elementData Array is empty
int oldCapacity = elementData.length;
// There will be a 1.5 Double expansion
// The following sentence can be understood as oldCapacity add oldCapacity Divide 2
int newCapacity = oldCapacity + (oldCapacity >> 1);
// nexCapacity = 0 - 1 < 0? false
if (newCapacity - minCapacity < 0) // Meet the conditions
// minCapacity be equal to 10 Assign a value to newCapacity
newCapacity = minCapacity;
// Make a maximum value judgment , Is it beyond
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
// At this time, a Arrays.copyOf Complete a capacity expansion
elementData = Arrays.copyOf(elementData, newCapacity);
}
6, The illustration , It was like this when I came out for the first time 
7, The second time you add
private void ensureExplicitCapacity(int minCapacity) {
modCount++; // The number of modifications is increased
// overflow-conscious code
// minCapacity be equal to 2 elementData.length be equal to 10
// 2-10 = -8 ,-8 No more than 0 So it doesn't meet the conditions
if (minCapacity - elementData.length > 0) // Not meeting the conditions
// The current method will not be called
grow(minCapacity);
}
8, Suppose the current element bits are used up , Need to expand
private void grow(int minCapacity) {
// overflow-conscious code
// elementData.length = 10 therefore oldCapacity be equal to 10
int oldCapacity = elementData.length;
// int newCapacoty = 10 + (10 / 2);
// The result is 15
int newCapacity = oldCapacity + (oldCapacity >> 1);
// It's the same below , It was explained above that
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
// New newCapacity( New capacity ) And the previous array Put it in and expand it
elementData = Arrays.copyOf(elementData, newCapacity);
}
9, The diagram means 
10, Push in , For each increase 1.5 Times the speed to increase
边栏推荐
- Research Report on the overall scale, major manufacturers, major regions, products and applications of micro hydraulic cylinders in the global market in 2022
- [fluent] dart function (function composition | private function | anonymous function | function summary)
- Research Report on ranking analysis and investment strategic planning of RFID market competitiveness of China's industrial manufacturing 2022-2028 Edition
- Longest public prefix of leetcode
- Research Report on market supply and demand and strategy of microplate instrument industry in China
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of precoated metallic coatings in the global market in 2022
- Makefile: usage of control functions (error, warning, info)
- Lantern Festival, come and guess lantern riddles to win the "year of the tiger Doll"!
- Structured text language XML
- I drew a Gu ailing with characters!
猜你喜欢

Interested parties add me for private chat

Spend more time with your computer on this special holiday, HHH

rwctf2022_ QLaaS

AMD's largest transaction ever, the successful acquisition of Xilinx with us $35billion

Customized Huawei hg8546m restores Huawei's original interface

Activation function - relu vs sigmoid

One week dynamics of dragon lizard community | 2.07-2.13
![[question brushing diary] classic questions of dynamic planning](/img/31/fcd8230f809d6178f11e7095c1ef94.jpg)
[question brushing diary] classic questions of dynamic planning

Research Report on ranking analysis and investment strategic planning of RFID market competitiveness of China's industrial manufacturing 2022-2028 Edition

Friends who firmly believe that human memory is stored in macromolecular substances, please take a look
随机推荐
1007 maximum subsequence sum (25 points) "PTA class a exercise"
Welfare | Pu Aries | liv heart co branded Plush surrounding new products are on the market!
Chinese Indian seasoning market trend report, technical dynamic innovation and market forecast
What are the preferential account opening policies of securities companies now? Is it actually safe to open an account online?
[C language] [sword finger offer article] - replace spaces
AES encryption CBC mode pkcs7padding filling Base64 encoding key 32byte iv16byte
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of the inverted front fork of the global market in 2022
Accounting regulations and professional ethics [16]
[shutter] the shutter plug-in is used in the shutter project (shutter plug-in management platform | search shutter plug-in | install shutter plug-in | use shutter plug-in)
China's crude oil heater market trend report, technological innovation and market forecast
Redis -- three special data types
[871. Minimum refueling times]
Who do you want to open a stock account? Is it safe to open a mobile account?
[CV] Wu Enda machine learning course notes | Chapter 12
AMD's largest transaction ever, the successful acquisition of Xilinx with us $35billion
Number of DP schemes
rwctf2022_ QLaaS
China's log saw blade market trend report, technological innovation and market forecast
Record the problems encountered by nodejs asynchronism
Common routines of compressed packets in CTF