Arraylist源码分析:
作者:互联网
*Arraylist源码分析:*
*DEFAULT_CAPACITY*** = 10;默认容量大小 ,如果没有向集合中添加任何元素的时候,集合的容量是0.添加一个元素之后,容量就变成10了。
Object[] *elementData* *存放元素的数组*
*Size* *集合的大小*
*Add() 添加操作*
*下面是比较重要的源码*
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!! size=0
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) { //现在 minCapacity=1
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)//1-0>0 条件成立
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//0
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;//newCapacity =1
if (newCapacity - MAX_ARRAY_SIZE > 0) 1-(Integer.MAX_VALUE - 8;)>0不成立
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);//赋值elementData 数组长度为1
}
*结论:ArrayList每次进行扩容都是原来的1.5倍。视频讲解https://www.bilibili.com/video/BV1zD4y1Q7Fw?p=12*
标签:分析,int,Arraylist,elementData,newCapacity,minCapacity,源码,size 来源: https://www.cnblogs.com/dongyaotou/p/14348956.html