当前位置:网站首页>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
边栏推荐
- China Indonesia advanced wound care market trend report, technological innovation and market forecast
- Who do you want to open a stock account? Is it safe to open a mobile account?
- China's crude oil heater market trend report, technological innovation and market forecast
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of multi-channel signal conditioners in the global market in 2022
- What is the difference between programming in real work and that in school?
- China plastic box market trend report, technological innovation and market forecast
- qwb2018_ core kernel_ rop
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of sound quality head simulators in the global market in 2022
- Internet Explorer ignores cookies on some domains (cannot read or set cookies)
- Micro SD Card Industry Research Report - market status analysis and development prospect forecast
猜你喜欢
[shutter] shutter layout component (Introduction to layout component | row component | column component | sizedbox component | clipoval component)
Hot backup routing protocol (HSRP)
Web3js method to obtain account information and balance
qwb2018_ core kernel_ rop
Go language learning summary (5) -- Summary of go learning notes
[shutter] statefulwidget component (floatingactionbutton component | refreshindicator component)
How does esrally perform simple custom performance tests?
[error record] the command line creates an error pub get failed (server unavailable) -- attempting retry 1 in 1 second
JDBC | Chapter 4: transaction commit and rollback
Review of the latest 2022 research on "deep learning methods for industrial defect detection"
随机推荐
In depth research and investment feasibility report of global and Chinese isolator industry, 2022-2028
Go language learning summary (5) -- Summary of go learning notes
MySQL learning notes (Advanced)
Import a large amount of data to redis in shell mode
AES encryption CBC mode pkcs7padding filling Base64 encoding key 32byte iv16byte
How does esrally perform simple custom performance tests?
Longest public prefix of leetcode
Add two numbers of leetcode
Construction and maintenance of business website [3]
Backpack template
AMD's largest transaction ever, the successful acquisition of Xilinx with us $35billion
Sword finger offer (I) -- handwriting singleton mode
Record the problems encountered by nodejs asynchronism
Research Report on the overall scale, major manufacturers, major regions, products and applications of building automation power meters in the global market in 2022
China's noise meter market trend report, technical dynamic innovation and market forecast
Research Report on plastic antioxidant industry - market status analysis and development prospect forecast
China's crude oil heater market trend report, technological innovation and market forecast
Check the confession items of 6 yyds
Golang string segmentation
2021 software security report: open source code, happiness and disaster depend on each other?