当前位置:网站首页>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
边栏推荐
- Go web programming practice (2) -- process control statement
- Go language learning summary (5) -- Summary of go learning notes
- Who do you want to open a stock account? Is it safe to open a mobile account?
- 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
- [C language] [sword finger offer article] - replace spaces
- China plastic bottle and container market trend report, technological innovation and market forecast
- [shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)
- Analyze comp-206 advanced UNIX utils
- Cloud computing technology [2]
- Friends who firmly believe that human memory is stored in macromolecular substances, please take a look
猜你喜欢

Interested parties add me for private chat

Volvo's first MPV is exposed! Comfortable and safe, equipped with 2.0T plug-in mixing system, it is worth first-class

Web3js method to obtain account information and balance

It is said that this year gold three silver four has become gold one silver two..

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

Internal/validators js:124 throw new ERR_ INVALID_ ARG_ Type (name, 'string', value) -- solution

I drew a Gu ailing with characters!

qwb2018_ core kernel_ rop

Today, I met a Alipay and took out 35K. It's really sandpaper to wipe my ass. it's a show for me

One week dynamics of dragon lizard community | 2.07-2.13
随机推荐
I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy
Research Report on market supply and demand and strategy of microplate instrument industry in China
China's log saw blade market trend report, technological innovation and market forecast
Go web programming practice (1) -- basic syntax of go language
Share the easy-to-use fastadmin open source system - Installation
Interested parties add me for private chat
Research Report on the overall scale, major manufacturers, major regions, products and applications of capacitive voltage transformers in the global market in 2022
Research Report on the overall scale, major manufacturers, major regions, products and applications of sliding door dampers in the global market in 2022
Huawei Hongmeng watch achieves fireworks display effect on New Year's Eve
Construction and maintenance of business websites [4]
Backpack template
Structured text language XML
Go cache of go cache series
One week dynamics of dragon lizard community | 2.07-2.13
Research Report on the overall scale, major manufacturers, major regions, products and applications of swivel chair gas springs in the global market in 2022
AES encryption CBC mode pkcs7padding filling Base64 encoding key 32byte iv16byte
[dynamic planning] p1220: interval DP: turn off the street lights
Research and Analysis on the current situation of China's clamping device market and forecast report on its development prospect
Research Report on the overall scale, major manufacturers, major regions, products and applications of outdoor vacuum circuit breakers in the global market in 2022
Happy Lantern Festival! Tengyuanhu made you a bowl of hot dumplings!