ArrayList源码剖析
1.源码剖析:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;//序列版本号
private static final int DEFAULT_CAPACITY = 10;//初始容量为10
private static final Object[] EMPTY_ELEMENTDATA = {};//Object数组,用来实例化不带容量大小的构造函数 指定ArrayList容量为0时,返回空数组
private transient Object[] elementData;//保存ArrayList中元素的数组
private int size; //元素个数 ArrayList实际大小
public ArrayList(int initialCapacity) {
//ArrayList带容量大小的构造函数
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];//新建一个数组初始化elementData
}
public ArrayList() {//不带参数的构造函数
super();
this.elementData = EMPTY_ELEMENTDATA;//使用空数组初始化elementData
}
public ArrayList(Collection<? extends E> c) {//用Collection来初始化ArrayList
elementData = c.toArray(); //将Collection中的内容转换成数组初始化elementData
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
public void trimToSize() {//修剪数组容量大小
modCount++;
//当ArrayList中的元素个数小于elementData数组大小时,重新修整elementData到size大小
if (size < elementData.length) {
elementData = Arrays.copyOf(elementData, size);
}
}
//扩容,该方法是提供给外界调用的,真正扩容是在下面的private方法里
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != EMPTY_ELEMENTDATA)
// any size if real element table
? 0
// larger than default for empty table. It's already supposed to be
// at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
//如果是个空数组
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//取minCapacity和10的较大者
}
//如果数组已经有数据了
ensureExplicitCapacity(minCapacity); //101
}
private void ensureExplicitCapacity(int minCapacity) {//确保数组容量大于ArrayList中元素个数
modCount++;//将修改统计数+1
// overflow-conscious code
101 - 100
if (minCapacity - elementData.length > 0)//如果实际数据容量大于数组容量,就给数组扩容
grow(minCapacity);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {//具体扩容方法
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//在原来容量的基础上加上oldCapacity/2,即默认1.5倍扩容
if (newCapacity - minCapacity < 0) //150 -101
newCapacity = minCapacity; 10
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
public int size() {//返回ArrayList的实际大小
return size;
}
public boolean isEmpty() {//判断ArrayList是否为空
return size == 0;
}
public boolean contains(Object o) {//判断ArrayList是否包含Object o
return indexOf(o) >= 0;
}
public int indexOf(Object o) {//正向查找,返回元素的索引值
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
public int lastIndexOf(Object o) {//逆向查找,返回元素的索引值
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
public Object clone() {//克隆函数
try {
@SuppressWarnings("unchecked")
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);//将当前ArrayList的全部元素拷贝到v中
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
//返回一个Object数组,包含ArrayList中所有的元素
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
//返回ArrayList的模板数组
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {//传入一个空的数组
//如果数组a的大小 < ArrayList的元素个数,
//则新建一个T[]数组,大小为ArrayList元素个数,并将ArrayList全部拷贝到新数组中。
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
//如果数组a的大小 >= ArrayList的元素个数,
//则将ArrayList全部拷贝到新数组a中。
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
// Positional Access Operations
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
public E get(int index) {//获取index位置的元素值
rangeCheck(index);//首先判断index的范围是否合法
return elementData(index);
}
public E set(int index, E element) {//将index位置的值设为element,并返回原来的值
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
public boolean add(E e) {//将e添加到ArrayList中
/*新增一个数据的源码非常简单,如果不看ensureCapacityInternal(size + 1);这一句代码,实际上就是往数组的size索引这个位置放入一个数据。
size是ArrayList的大小。注意,这里的size不是数组的大小,而是数组里真正存在数据的大小,也即是ArrayList的大小。
比如ArrayList的size是10,但是数据的长度有可能是100,只有前10个位置存放了真正的数据。*/
ensureCapacityInternal(size + 1); // 101 Increments modCount!!
elementData[size++] = e;
return true;
}
public void add(int index, E element) {//将element添加到ArrayList的指定位置
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
//将index以及index之后的数据复制到index+1的位置往后,即从index开始向后挪了一位
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;//然后在index处插入element
size++;
}
public E remove(int index) {//删除ArrayList指定位置的元素
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)//向左挪一位,index位置原来的数据已经被覆盖了
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//多出来的最后一位置空
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public boolean remove(Object o) {//删除ArrayList中指定的元素
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的快速删除与上面的public普通删除区别在于,没有进行边界判断以及不返回删除值
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
public void clear() {//清空ArrayList,将全部元素置为null
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
//将集合C中所有的元素添加到ArrayList中
public boolean addAll(Collection<? extends E> c) {//求并集
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
//在原来数组的后面添加c中所有的元素
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
//从index位置开始,将集合C中所欲的元素添加到ArrayList中
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;
if (numMoved > 0)
//将index开始向后的所有数据,向后移动numNew个位置,给新插入的数据腾出空间
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
//将集合C中的数据插到刚刚腾出的位置
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
//删除从fromIndex到toIndex之间的数据,不包括toIndex位置的数据
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
private void rangeCheck(int index) {//下标检测
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void rangeCheckForAdd(int index) {//add和addAll方法中的范围检测
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
//删除ArrayList中所有集合C中包含的数据
public boolean removeAll(Collection<?> c) {//求差集
return batchRemove(c, false);
}
//删除ArrayList中除了集合C中包含的数据外的其他所有数据
public boolean retainAll(Collection<?> c) {//求交集
return batchRemove(c, true);
}
private boolean batchRemove(Collection<?> c, boolean complement) {//批量删除
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
//java.io.Serializable的写入函数
//将ArrayList的“容量、所有的元素值”都写入到输出流中
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
//java.io.Serializable的读取函数:根据写入方式读出
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
2.细节补充:
- ArrayList是基于动态数组实现的,在增删的时候,需要数组的拷贝复制。
- ArrayList的默认初始化容量是10,每次扩容都是增加原先的0.5倍,也就是*1.5。
- 删除元素时不会减少容量,如果想减少容量,则需要调用trimToSize()方法。
- 线程不安全 可以存放NULL。