当前位置:网站首页>Detailed explanation of ArrayList expansion
Detailed explanation of ArrayList expansion
2022-07-01 17:49:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
This article discusses ArrayList Expansion process
ArrayList At the bottom is an array elementData, Used to store inserted data . The initial size is 0, When data is inserted , Default size DEFAULT_CAPACITY = 10. If you're creating ArrayList When it comes to initialCapacity, Then the initial size is ArrayList
1. Verify the code example of capacity expansion
As you can see from the example , When adding elements , If the number of elements +1> Current array length 【size + 1 > elementData.length】 when , super-popular , The size of the expanded array is : oldCapacity + (oldCapacity >> 1)
Pass the contents of the old array Array.copyOf Copy all to the new array , At this time, the old and new lists size Same size , but elementData The length is different from the capacity
Be careful : Expansion is not strict 1.5 times , Is to shift the length of the array one bit to the right before expansion + The length of the array before expansion
public class SimpleTest {
public static void main(String[] args) {
ArrayList list = new ArrayList();
int size = 0;
for (int i = 0; i < 100; i++) {
list.add(i);
if(getCapacity(list)>size) {
System.out.println("capacity:"+getCapacity(list) + ",size:"+list.size());
size = getCapacity(list);
}
}
}
public static Integer getCapacity(ArrayList list) {
Integer length = null;
Class clazz = list.getClass();
Field field;
try {
field = clazz.getDeclaredField("elementData");
field.setAccessible(true);
Object[] object = (Object[]) field.get(list);
length = object.length;
return length;
} catch (Exception e) {
e.printStackTrace();
}
return length;
}
}The operation results are as follows :
capacity:10,size:1 capacity:15,size:11 capacity:22,size:16 capacity:33,size:23 capacity:49,size:34 capacity:73,size:50 capacity:109,size:74
2. Expansion related source code
public boolean add(E e) {
// Called a ensureCapacityInternal Method , Ensure that the array subscript does not cross the bounds
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// The new capacity is expanded to about 1.5 times , Moving one bit to the right is equivalent to dividing the original value by 2, Expansion is not strict 1.5 position
int newCapacity = oldCapacity + (oldCapacity >> 1);
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:
elementData = Arrays.copyOf(elementData, newCapacity);
}3. Why press about 1.5 Double expansion
Size selection of expansion factor , The following situations need to be considered :
- The expansion capacity cannot be too small , Prevent frequent expansion , Frequently apply for memory space + Arrays are copied frequently
- The expansion capacity should not be too large , Need to make full use of space , Avoid wasting too much space ;
In order to make full use of the previously allocated memory space , It's better to set the growth factor to 1<k<2.
k=1.5 when , You can make full use of the space already released in front . If k >= 2, The new capacity is just right, which is always greater than the capacity of all abandoned arrays in the past
And make full use of the shift operation ( Moves to the right one ), Reduce floating point numbers or operation time and number of operations
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/130890.html Link to the original text :https://javaforall.cn
边栏推荐
- MySQL -- explain performance optimization
- Product service, operation characteristics
- People help ant help task platform repair source code
- (十七)DAC转换实验
- Kernel stray cat stray dog pet adoption platform H5 source code
- Depth first traversal and breadth first traversal [easy to understand]
- Gameframework eating guide
- RadHat搭建内网YUM源服务器
- 股票万1免5证券开户是合理安全的吗,怎么讲
- Detailed explanation of string's trim() and substring()
猜你喜欢

ISO 27001 Information Security Management System Certification

Thinkphp6 - CMS multi wechat management system source code

transform. Forward and vector3 Differences in the use of forward

New 95 community system whole station source code

Oom caused by improper use of multithreading

Euler function: find the number of numbers less than or equal to N and coprime with n

Gold, silver and four want to change jobs, so we should seize the time to make up

Mysql database - Advanced SQL statement (2)

整形数组合并【JS】

Penetration practice vulnhub range Keyring
随机推荐
RadHat搭建内网YUM源服务器
线上开通ETF基金账户安全吗?有哪些步骤?
Report on research and investment prospects of UHMWPE industry in China (2022 Edition)
Reflective XSS vulnerability
String的trim()和substring()详解
Is Huishang futures a regular futures platform? Is it safe to open an account in Huishang futures?
China PBAT resin Market Forecast and Strategic Research Report (2022 Edition)
Openlayers 自定义气泡框以及定位到气泡框
Unity3d extended toolbar
In depth Research Report on China's disposable sanitary products production equipment industry (2022 Edition)
Wechat applet blind box - docking wechat payment
(27) Open operation, close operation, morphological gradient, top hat, black hat
Can hero sports go public against the wind?
JDBC:深入理解PreparedStatement和Statement[通俗易懂]
剑指 Offer 20. 表示数值的字符串
Roewe rx5's "a little more" product strategy
Is it safe to open an ETF account online? What are the steps?
Leetcode records - sort -215, 347, 451, 75
反射型XSS漏洞
Sword finger offer 20 String representing numeric value