在线
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(this, ...)
)。
现在,当您调用
list2.clear();
clear()
方法的代码将从AbstractList
继承给SubList
,并被调用。
public void clear() {
removeRange(0, size());
}
这将在内部调用SubList
中重写的removeRange
方法。
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
。
sublist(0, 2)
中的列表中有4个元素? - phlaxyr