前沿
ArrayList使用频率较高,所以弄懂这个类极其重要。以下代码基于jdk1.8
## 正文
ArrayList是一个数组队列。它的容量可以动态增长
- 属性
// 存放数据的数组
transient Object[] elementData;
// list的长
private int size
ArrayList比较重要的两个属性:elementData和size
(1)elementData用来存放实际的数据。elementData是个动态的数据,根据list的容量而动态的增长
(2)size 则是动态数组的实际大小
- 构造函数
/**
* Constructs an empty list with an initial capacity of ten.
*/ //初始化默认容量的空列表。默认为10,待add第一个元素才初始化数组
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
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;
}
}
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/ //初始化指定list容量
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);
}
}
三个构造方法都不难理解。主要操作都是给elementData赋值
第一个构造方法,标记为默认容量的list。默认容量为10,暂不初始化容量
第二个构造方法,传入集合类型,初始化elementDat
第三个构造方法,指定容量大小初始化elementData
- 增加方法
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/ //添加一个元素
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); // 对数组进行复制,目的是空出index的位置插入element,并将index后的元素移一个位置
elementData[index] = element;
size++;
}
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray(); // 将c转换为数组
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount // 扩容检查
System.arraycopy(a, 0, elementData, size, numNew); // 将c添加至list的数据尾部
size += numNew; // 更新容器大小
return numNew != 0;
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index); // 检查索引是否越界,只能插入已有元素的位置
Object[] a = c.toArray(); // c转换为数组
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount // 扩容检查
int numMoved = size - index; // 计算需要移动的长度(index之后的元素个数)
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved); // 数组复制,空出index到index+numNew的位置,即将数组index后的元素向右移动numNew个位置
System.arraycopy(a, 0, elementData, index, numNew); // 将要插入的集合元素复制到数组中空出的位置
size += numNew; // 更新容量大小
return numNew != 0;
}
add的四个方法,主要是检查list的容量是否足够,添加元素。若是容量不足,则扩容。添加元素区分在末端添加还是在中间添加。若是在中间添加,则要移动后面的元素,空出位置添加元素。
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { // 默认10容量,第一次添加元素才初始化数组
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code // 需要最小的容量,比数组的容量小,就扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
// 扩容的算法
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); // 新扩容的数组长度=旧的容量+旧的容量/2(向下取整)。譬如,容量为10,扩容后为10+5=15,譬如,容量为9,扩容后为9+4=13
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); // 进行数据拷贝,Arrays.copyOf底层实现是System.arrayCopy()
}
- 删除方法
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 // size减一,数组最后一个元素置空
return oldValue;
}
public boolean remove(Object o) {
if (o == null) { // 对要删除的元素进行null判断
for (int index = 0; index < size; index++)
if (elementData[index] == null) { // null值需要用==比较
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) { // 非null用equal比较
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++;
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);
}
// 批量删除,遍历c集合,判断数组是否包含元素。若不是,留下该元素
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++) //清除数组里没用的元素,方便gc
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
// figure out which elements are to be removed //标记需要移除的元素,标记为true
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
int removeCount = 0;
final BitSet removeSet = new BitSet(size); // 存放true false的数组
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i); // 将索引处的位设置为 true
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// shift surviving elements left over the spaces left by removed elements //
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i); // 返回设置为 false 的位的索引
elementData[j] = elementData[i]; // false 不需要移除,元素往前挪
}
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
总结
- ArrayList实际上是一个通过一个数组去保存数据的。
- 当ArrayList容量不足以容纳新增元素时,会重新设置容量。
- 初始化ArrayList,若是知道size尽可能的指定容量,避免触发容量扩容