我觉得这篇文章写的很不错,标记一下
参考文章:
Java面试专项——集合专题一(ArrayList)–万字读懂ArrayList底层原理
我看了这篇文章只做个总结:
ArrayList中的成员变量:
/**
* Default initial capacity.
*/
// 默认容量为10,一般是在集合进行初始化扩容的时候
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {}; // 空数组
/**
* 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 = {}; // 默认的空数组
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
// 真正的集合内容存放在这里面
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
// 集合元素个数,不是集合的长度
private int size;
- ArrayList是使用size属性来确定数组是否越界,并非构造方法public ArrayList(int initialCapacity)中的initialCapacity。
- size表示的是数组中元素的数量,并非数组的容量。
- ArrayList的容量是elementData数组的长度,ArrayList中包含的元素的个数是size的大小
- ArrayList的扩容操作其实是在
grow()
方法中进行的,前面的操作都是用来判断是否满足扩容的条件 - 扩容后的容量计算:
int newCapacity = oldCapacity + (oldCapacity >> 1)
,一个整形变量右移一位,num>>1,如果num为正偶数,那么num>>1等价于num/2。如果num为正奇数,那么num>>1等价于num/2向下取整。所以ArrayLis容量不足时,扩容50%或者扩容到原来的1.5倍的说法并不严谨