ArrayList源码阅读记录
- 构造函数
// 初始容量
private static final int DEFAULT_CAPACITY = 10;
// 空数组
private static final Object[] EMPTY_ELEMENTDATA = {};
// 默认数组
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 存放元素数组
transient Object[] elementData;
// 数组大小
private int size;
// 默认构造
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public ArrayList(int initialCapacity) {
// initialCapacity:初始容量
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
this.elementData = EMPTY_ELEMENTDATA;
}
}
- index()/size()
// 获取集合大小
public int size() {
return size;
}
// 判断集合是否为空
public boolean isEmpty() {
return size == 0;
}
// 判断是否存在o元素
public boolean contains(Object o) {
// 调用indexOf方法判断是否含有o元素
return indexOf(o) >= 0;
}
// 获取第一个o元素下标
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;
}
- get()/set():获取/覆盖元素
// 获取index下标的元素
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
// 替换index位置元素
public E set(int index, E element) {
rangeCheck(index);
// 取出index位置的元素
E oldValue = elementData(index);
// 替换为element
elementData[index] = element;
return oldValue;
}
// 判断下标是否越界
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
- add():增加元素
// 增加元素
public boolean add(E e) {
// 扩容
ensureCapacityInternal(size + 1);
// 扩容之后把元素添加到size++
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
// 集合为空,赋初始容量
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
// 赋DEFAULT_CAPACITY,minCapacity中的最大值
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
if (minCapacity - elementData.length > 0)
// 扩容
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
// 扩容1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 扩容之后的容量 < 传入的容量 例:oldCapacity = 1
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 容量的最大值
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0)
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
// 新增指定index位置元素element
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // 扩容
/*
* 复制elementData数组中index下标之后的所有元素
* 复制到elementData中,从下标index + 1开始复制
* elementData:源数组, 从index开始复制,复制size - index个
* elementData目标数组, index + 1
*/
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
// index位置的元素已经复制到index + 1,把element元素放入index位置
elementData[index] = element;
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); // 扩容
// 把a数组复制到elementData中,从size下标开始复制
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
/*
* 指定下标增加元素集合
* 思路:a集合元素(a.length)从下标index开始插入到elementData中
* elementData分为两部分:index之前(firstIndex)和index之后(lastIndex),形成的新数组为 firstIndex + a.length + lastIndex
* 复制lastIndex元素到a之后,即index + a.length
* */
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // 扩容
int numMoved = size - index;
// 复制index之后的元素
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
// 把a的全部元素复制到elementData中
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
- remove():移除元素
/*
* 移除index位置元素:
* 思路:复制index + 1之后的所有元素,从index开始覆盖,最后一位赋空
*/
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
// fastRemove(index); // 请看下方方法
// index位置之后元素个数
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null;
return oldValue;
}
/*
* 移除o元素
* 找到o元素的下标,重复上方方法的步骤
*/
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;
}
// 移除与c集合相同元素
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c); // 判断集合是否为空
return batchRemove(c, false);
}
// 移除与c集合不同元素
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
// 移除元素,已complement = false为例
private boolean batchRemove(Collection<?> c, boolean complement) {
// 注意complement的值
final Object[] elementData = this.elementData;
// r:循环下标 , w:修改次数
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
// complement为false:循环出所有不相同的值
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// 把未循环的元素直接复制在elementData[w--]之后
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
// w下标之前都是不相同的值,直接清除w下标开始之后的值
// w是修改次数,数组下标是从0开始的,所以不相同元素的最后一个下标为 w--
if (w != size) {
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
- clear():清空元素
// 清空数组元素
public void clear() {
modCount++;
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
- 不常用方法
// 长度去空
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData =
(size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size);
}
}
// 克隆集合
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
// 赋值elementData元素值到a数组中
public <T> T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
移除和清空元素的时候,只是size改变,并没有对应减少集合的容量。