ArrayList的继承体系
主要属性
// 默认的容量
private static final int DEFAULT_CAPACITY = 10;
// 空数组,如果传入的容量为0的时候使用
private static final Object[] EMPTY_ELEMENTDATA = {};
// 空数组,传传入容量时使用,添加第一个元素的时候会重新初始为默认容量大小
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 元素存储数据
transient Object[] elementData; // non-private to simplify nested class access
// 元素的个数
private int size;
构造方法
// 初始化容量的构造方法
public ArrayList(int initialCapacity) {
// 容量大于0,新创建个数组
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
// 容量等于0,创建个空数组
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
// 小于0抛出异常
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
// 如果没有传入初始容量,则使用空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA
// 使用这个数组是在添加第一个元素的时候会扩容到默认大小10
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
// 添加元素集合构造方法
public ArrayList(Collection<? extends E> c) {
// 集合转数组
elementData = c.toArray();
// 设置数组的长度,判断是否为0
// 不为0,拷贝数组
// 为0,设置空数组
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
// 检查c.toArray()返回的是不是Object[]类型,如果不是,重新拷贝成Object[].class类型
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
为什么c.toArray();返回的有可能不是Object[]类型呢?
public class ArrayTest {
public static void main(String[] args) {
Father[] fathers = new Son[]{};
// 打印结果为class [Lcom.coolcoding.code.Son;
System.out.println(fathers.getClass());
List<String> strList = new MyList();
// 打印结果为class [Ljava.lang.String;
System.out.println(strList.toArray().getClass());
}
}
class Father {}
class Son extends Father {}
class MyList extends ArrayList<String> {
/**
* 子类重写父类的方法,返回值可以不一样
* 但这里只能用数组类型,换成Object就不行
* 应该算是java本身的bug
*/
@Override
public String[] toArray() {
// 为了方便举例直接写死
return new String[]{"1", "2", "3"};
}
}
添加元素
添加元素到末尾,平均时间复杂度为O(1)。
// 添加元素
public boolean add(E e) {
// 检查是否需要扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
// 元素个数+1,设置数组位置为插入元素
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
// 判断数组是否为默认的空输入
// 默认的空数组设置容量为默认的capacity大小
// 否则返回size+1
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
// 操作次数+1
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
// 扩容
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
// 数组长度
int oldCapacity = elementData.length;
// 容量大小 = 原数组长度 + 原数组长度的0.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 如果新容量发现比需要的容量还小,则以需要的容量为准
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 如果新容量发现比最大容量还大,则使用最大容量
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 拷贝出来原有的数据
elementData = Arrays.copyOf(elementData, newCapacity);
}
添加元素到指定位置
public void add(int index, E element) {
// 判断是否越界
rangeCheckForAdd(index);
// 扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
// 将index及之后的元素,向后挪1位
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
// 设置添加数据位置
elementData[index] = element;
// 数组大小+1
size++;
}
// 校验是否越界
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
添加集合
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;
// 返回添加集合是否长度为0
return numNew != 0;
}
get
获取指定索引位置的元素,时间复杂度为O(1)。
public E get(int index) {
// 判断数组是否越界
rangeCheck(index);
// 返回数组第index个元素
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
remove
删除指定索引位置的元素,时间复杂度为O(n)。
public E remove(int index) {
// 检查是否越界
rangeCheck(index);
// 操作次数+1
modCount++;
// 获取数组
E oldValue = elementData(index);
int numMoved = size - index - 1;
// 判断删除的元素是否是最后一个
// 不是,把index之后的元素向前移动一位
// 是,设置size-- 最后一位为null,协助GC
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
// 返回原数据
return oldValue;
}
指定元素删除
删除指定元素值的元素,时间复杂度为O(n)。
public boolean remove(Object o) {
// 判断元素是否为空
// 为空遍历找出第一个为null的元素,并将其快速删除
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) {
// 操作次数+1
modCount++;
int numMoved = size - index - 1;
// 判断是否最后一位
// 不是最后一位,进行将index后的数据向前移动一位
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// size-1 设置最后一位元素为空,协助GC
elementData[--size] = null; // clear to let GC do its work
}
retainAll
// 求两个集合的交集
public boolean retainAll(Collection<?> c) {
// 判断是否为空
Objects.requireNonNull(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 {
// 遍历整个数组,如果c中包含该元素,则把该元素放到写指针的位置(以complement为准)
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.
// 正常来说r最后是等于size的,除非c.contains()抛出了异常
if (r != size) {
// 如果c.contains()抛出了异常,则把未读的元素都拷贝到写指针之后
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
// 将写指针之后的元素置为空,帮助GC
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
// 设置数组长度
size = w;
// 设置修改状态
modified = true;
}
}
// 有修改返回true
return modified;
}
removeAll
public boolean removeAll(Collection<?> c) {
// 集合c不能为空
Objects.requireNonNull(c);
// 同样调用批量删除方法,这时complement传入false,表示删除包含在c中的元素
return batchRemove(c, false);
}
总结
- ArrayList内部使用数组存储元素,当数组长度不够时进行扩容,每次加一半的空间,ArrayList不会进行缩容;
- ArrayList支持随机访问,通过索引访问元素极快,时间复杂度为O(1);
- ArrayList添加元素到尾部极快,平均时间复杂度为O(1);
- ArrayList添加元素到中间比较慢,因为要搬移元素,平均时间复杂度为O(n);
- ArrayList从尾部删除元素极快,时间复杂度为O(1);
- ArrayList从中间删除元素比较慢,因为要搬移元素,平均时间复杂度为O(n);
- ArrayList支持求并集,调用addAll(Collection<? extends E> c)方法即可;
- ArrayList支持求交集,调用retainAll(Collection<? extends E> c)方法即可;
- ArrayList支持求单向差集,调用removeAll(Collection<? extends E> c)方法即可;