继承关系
public class ArrayList extends AbstractList
implements List, RandomAccess, Cloneable, java.io.Serializable
public abstract class AbstractList extends AbstractCollection implements List
public abstract class AbstractCollection implements Collection
RandomAccess
public interface RandomAccess {
}
一个空接口,起到一个标记的作用,有此接口的集合,通过下标来获取元素的速度比Iterator遍历器快
成员变量
1.默认数组容量
private static final int DEFAULT_CAPACITY = 10;
2.默认空数组
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
3.底层数据结构是数组
transient Object[] elementData;
数组类型是object,transient表示该数组不能被序列化
4.数组中的元素个数
private int size;
关键方法
1.构造方法
//构造方法1
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
//构造方法2
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//构造方法3
public ArrayList(Collection extends E> c) {
elementData = c.toArray();
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;
}
}
构造方法1
根据指定容量,创建一个对象数组
构造方法2
初始化一个空对象数组
构造方法3
创建一个和指定集合一样的对象数组
2.添加元素
//在末尾添加元素
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//在指定位置添加元素
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
//在末尾添加一个集合
public boolean addAll(Collection extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
//在指定位置添加一个集合
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)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
分析
在指定位置添加元素的时候会调用rangeCheckForAdd方法
//要求0<=index<=size,否则抛异常
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
无论是哪个add方法,都必调用ensureCapacityInternal方法
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
如果数组是空数组,则minCapacity==10,这就是为什么在调用ArrayList的空构造方法时,默认容量是10的原因了。
该方法会调用ensureExplicitCapacity方法
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
modCount记录ArrayList的修改次数
当容量不能达到minCapacity时,会调用grow方法增加容量
这个minCapacity的值,对于add来说是size+1,对于addAll来说是size+要添加的集合的size
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
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);
}
新的容量首先扩张为旧容量的1.5倍
如果扩充后的容量仍然小于minCapacity,则新的容量扩充为minCapacity
如果新的容量超过最大容量,则调用hugeCapacity方法
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
从这里可以看出ArrayList的最大容易是 Integer.MAX_VALUE,而不是 Integer.MAX_VALUE-8
当新的容量计算好之后,就之前的数组中的元素一一复制到新容量的数组里面。
3.数组扩容
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
我们知道数组在扩容过程中,需要数组的复制操作,这个挺耗时的,为了减少扩容的操作,可以直接调用该方法,直接指定数组的容量。但缺点就是浪费内存。
4. 删除元素
//删除指定位置上的元素
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
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
return oldValue;
}
//删除指定元素
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 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 boolean removeAll(Collection> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
public boolean retainAll(Collection> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
//complement为ture,保留公共元素,为false,去除本集合中和指定集合一样的元素
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;
}
分析
删除操作,会先计算出要删除元素的位置,然后将该位置后面的元素统一像前移动一位,同时size-1
删除操作不会改变数组的容量
5.修改,查询元素
//修改指定位置的元素,并返回该位置之前的元素
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
//根据下标获取元素
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
其他方法就不一一说明了
总结
ArrayList是一个动态可扩容的数组
当通过空构造函数创建ArrayList时,默认容量为10