ArrayList本质就是一个动态数组
属性:
// 集合默认大小
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;
初始化操作:
无参构造:
/**
* Constructs an empty list with an initial capacity of ten.
* 直接给存储数据的数组对象赋值了一个空数组 this.elementData = {}
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
有参构造:
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
//当前传入的大小是否大于0,如果大于0,则创建一个等同于当前值大小的数组,赋值给this.elementData
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
//如果等于0,则this.elementData直接赋值一个空数组
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
//否则直接抛出异常,数字非法
} else {
throw new IllegalArgumentException(“Illegal Capacity: “+
initialCapacity);
}
}
方法:
add():
第一次add:
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return true (as specified by {@link Collection#add})
*/
public boolean add(E e) {
//判断集合是否需要扩容,如果需要扩容则进行扩容
//第一次add,size默认为0,如果用的无参构造,没有对集合指定大小,则elementData={}
ensureCapacityInternal(size + 1); // Increments modCount!!
//第一次则等同为elementData[1] = e
_ _elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//calculateCapacity是对集合大小进行计算,ensureExplicitCapacity对集合进行扩容
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//如果当前的elementData是一个空数组,也就是还没有add值,则走if里的代码
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//DEFAULT_CAPACITY = 10,第一次add则minCapacity = 1,两者取最大值,直接返回10,所以ArrayList的默 认初始化大小为10
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
//如果elementData不为空,直接返回当前的minCapacity
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//由于是第一进行add,minCapacity = 10,elementData = {},所以条件成立 10 - 0 = 10 > 0
//如果指定了大小,elementData != {},则第一次add不需要扩容,走到这里就结束了
_if (minCapacity - elementData.length > 0)
//真正对集合进行扩容_
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 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
//第一次add,oldCapacity = 0
_int oldCapacity = elementData.length;
//0>>1 = 0,所以newCapacity = 0
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 0 - 10 = -10 < 0,成立,则直接将minCapacity赋值给newCapacity_
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8,Integer的最大值大概十亿多,减八还是十亿多,所以基本不 //会到这里来,hugeCapacity实际上就是返回:
//(minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE : MAX_ARRAY_SIZE;
if (newCapacity - _MAX_ARRAY_SIZE _> 0)<br /> newCapacity = _hugeCapacity_(minCapacity);_// minCapacity is usually close to size, so this is a win:_<br />_ // 创建一个大小为10数组,将elementData拷贝进去-----到此结束,直接回到add方法中进行数组赋值_
_elementData = Arrays._copyOf(elementData, newCapacity);
}
第二次add:
public boolean add(E e) {
//由于第一次add的时候 size++了,所以当前size为1,elementData = {e,,,,,,,,,}
ensureCapacityInternal(size + 1); // Increments modCount!!
_ _elementData[size++] = e;
return true;
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//计算集合大小,此时elementData != {},所以直接返回minCapacity,此时minCapacity = 2
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
_// minCapacity = 2,不满足条件,说明不需要扩容,到此结束,直接返回add方法进行数组赋值_<br />_ _if (minCapacity - elementData.length > 0)<br /> grow(minCapacity);<br />}
第十一次add:
public boolean add(E e) {
//此时size = 10,elementData = {e,e,e,e,e,e,e,e,e,e}
ensureCapacityInternal(size + 1); // Increments modCount!!
_ _elementData[size++] = e;
return true;
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//计算集合大小,直接返回minCapacity,此时minCapacity = 11
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
_//11 - 10 = 1 > 0,成立,则说明此时集合需要扩容了_<br />_ _if (minCapacity - elementData.length > 0)<br /> grow(minCapacity);<br />}
private void grow(int minCapacity) {
// oldCapacity = 10
_int oldCapacity = elementData.length;
//10>>1 = 5,newCapacity = 15,(这里实际上每次扩容都是扩大当前容量的1.5倍)
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 15 - 11 = 4 > 0,直接走扩容方法
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - _MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//创建一个容量为15的数组,将elementData中的数组拷贝进去——到此结束,返回add方法进行数组赋值
_elementData = Arrays._copyOf(elementData, newCapacity);
}
get():
public E get(int index) {
//检查index的合法性
rangeCheck(index);
//简单的数组取值
return elementData(index);
}
private void rangeCheck(int index) {
if (index >= size)
//大于当前容量,抛出数组越界异常
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
set():
public E set(int index, E element) {
//检查index合法性
rangeCheck(index);
//获取当前原下标数据
E oldValue = elementData(index);
//赋值新数据
elementData[index] = element;
//返回老数据
return oldValue;
}
remove():
public E remove(int index) {
//检查index合法性
rangeCheck(index);
modCount++;<br /> _ //获取老数据_<br /> E oldValue = elementData(index);<br /> _ //numMoved:需要移动的数据量_<br /> int numMoved = size - index - 1;<br /> if (numMoved > 0)<br /> _//创建新数组对原数组进行覆盖_<br /> System._arraycopy_(elementData, index+1, elementData, index,<br /> numMoved);<br /> elementData[--size] = null; _// clear to let GC do its work_<br /> _//返回老数据_<br />_ _return oldValue;<br />}
FailFast机制:
modCount——每次对集合进行操作都会进行一次自增长
快速失败机制,Java集合类为了并发访问在集合迭代过程中,内部结构发生变化的一种保护措施。这种错误保护 机制为这种可能发生错误抛出:java.util.ConcurrentModificationException
