一、ArrayList相关属性
重要的部分都用了中文注释
/**
* 类注释
* 1、允许 put null 值,会自动扩容
* 2、size、isEmpty、get、set、add 等方法时间复杂度都是 O (1)
* 3、是非线程安全的,多线程情况下,推荐使用线程安全类:Collections#synchronizedList;
* 4、增强 for 循环,或者使用迭代器迭代过程中,如果数组大小被改变,会快速失败,抛出异常。
*/
private static final long serialVersionUID = 8683452581122892189L;
/**
* 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.
* elementData表示数组本身
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*当前数组的大小,没有用volatile修饰,不是线程安全的
* @serial
*/
private int size;
下面是ArrayList的父类AbstractList中定义了一个int型的属性,记录的是ArrayList的结构性变化次数,有变动就会+1
protected transient int modCount = 0;
二、初始化
/**
* Constructs an empty list with an initial capacity of ten.
* 无参数初始化,数组大小为空
* 这里注意ArrayList 无参构造器初始化时,默认大小是空数组,并不是 10,10 是在第一次 add 的时候扩容的数组值。
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
* 有参数初始化
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
//elementData保存数组
elementData = c.toArray();
//1、如果集合c数据有值,且集合元素类型不是Object的话,会被转成Object的
//2、如果c没有值,数组默认为空
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;
}
}
三、新增和扩容
新增源码
/**
* Appends the specified element to the end of this list.
* 确保数组大小是否足够,不够执行扩容。然后直接赋值,线程不安全
* 新增时,并没有对值进行严格的校验,所以 ArrayList 是允许 null 值的
* @param e element to be appended to this list
* @return true (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
扩容源码
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
//modCount需要+1
modCount++;
// overflow-conscious code
//如果期望的容量大于目前数组的长度就扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//扩容
private void grow(int minCapacity) {
// overflow-conscious code
//记录老的容量大小
int oldCapacity = elementData.length;
//新的容量大小=老的容量大小*1.5
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果新的容量大小 < 我们的期望值,扩容后的值就等于我们的期望值
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果扩容后的值 > jvm 所能分配的数组的最大值,那么就用 Integer 的最大值
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
//通过复制进行扩容,copyOf内部通过System.arraycopy方法实现拷贝。
elementData = Arrays.copyOf(elementData, newCapacity);
}
四、删除
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* i such that
* (o==null ? get(i)==null : o.equals(get(i)))
* (if such an element exists). Returns true if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
* 新增的时候是没有对 null 进行校验的,所以删除的时候也是允许删除 null 值的
* 找到值在数组中的索引位置,是通过 equals 来判断的,如果数组元素不是基本类型,需要我们关注 equals 的具体实现。
* @param o element to be removed from this list, if present
* @return true if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
/*
* Private remove method that skips bounds checking and does not
*
* return the value removed.
*/
private void fastRemove(int index) {
//modCount需要+1
modCount++;
//numMoved 表示删除 index 位置的元素后,需要从 index 后移动多少个元素到前面去
int numMoved = size - index - 1;
if (numMoved > 0)
//从 index +1 位置开始被拷贝,拷贝的起始位置是 index,长度是 numMoved
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
五、迭代器
/**
* An optimized version of AbstractList.Itr
* ArrayList这里实现了Iterator类
*/
private class Itr implements Iterator<E> {
//迭代过程中,下一个元素的位置
int cursor; // index of next element to return
//迭代过程中,上一个元素的位置
int lastRet = -1; // index of last element returned; -1 if no such
//迭代过程中,期望的版本号,初试为数组实际版本号modCount
int expectedModCount = modCount;
Itr() {}
//判断还有没有值可以迭代,有为1,没有为0
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
//如果有值可以迭代,迭代的值是多少
//next方法检验能不能继续迭代,然后找到迭代的值,并为下一次迭代做准备(cursor+1)
public E next() {
//迭代过程中,判断版本号有没有修改,有被修改,则抛出ConcurrentModificationException异常
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
// 版本号比较
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public void remove() {
//如lastRet < 0 了,说明元素已经被删除了
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
// -1 表示元素已经被删除,这里也防止重复删除
lastRet = -1;
//删除元素成功,数组当前 modCount 就会发生变化,这里会把 expectedModCount 重新赋值,下次迭代时两者的值就会一致了
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
六、线程安全
ArrayList 有线程安全问题的本质,是因为 ArrayList 自身的 elementData、size、modConut 在进行各种操作时,都没有加锁,而且这些变量的类型并非是可见(volatile)的,所以如果多个线程对这些变量进行操作时,可能会有值被覆盖的情况。类注释中推荐使用Collections#synchronizedList 来保证线程安全,SynchronizedList 是通过在每个方法上面加上锁来实现,虽然实现了线程安全,但是性能大大降低,具体实现源码:
public boolean add(E e) {
synchronized (mutex) {// synchronized 是一种轻量锁,mutex 表示一个当前 SynchronizedList
return c.add(e);
}
}