排队
list2 = list.subList(2, 5);
您正在调用从list 引用的ArrayList 的subList 方法。它的代码是这样的
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
所以在确认有效范围后list2将存储
的结果
new SubList(this, 0, fromIndex, toIndex);
其中private class SubList extends AbstractList<E> 是在ArrayList 内部定义的类,此构造函数的代码如下所示
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
因此其parent 字段将存储对原始ArrayList (new SubList(<b>this</b>, ...)) 的引用。
现在当你打电话时
list2.clear();
将调用SubList从AbstractList继承的clear()方法的代码
public void clear() {
removeRange(0, size());
}
这将在内部调用 removeRange 覆盖在 SubList 中
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
如你所见,结果你正在调用
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
你记得parent 持有对调用subList 的ArrayList 的引用。如此有效地调用clear,您正在从创建子列表的原始列表中调用removeRange。