Java 容器源码分析之 ArrayList(8)
 
- UID
- 1066743
|

Java 容器源码分析之 ArrayList(8)
子列表所谓的子列表,就是列表中指定范围内的一些元素,通过调用subList(int fromIndex, int toIndex)来获取。对子列表的操作会影响到父列表。通过子列表可以达到操作父列表中部分元素的目的,如只迭代部分范围内的元素,或者只对部分范围内的元素进行排序。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent;
private final int parentOffset;
private final int offset;
int size;
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;
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false;
checkForComodification();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
}
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
}
| 上面列出了ArrayList中使用的子列表的部分代码,SubList继承了AbstractList,并实现了RandomAccess接口。SubList中并没有向ArrayList那样有一个数组来存放元素,而是持有了父列表的引用,并保存了元素相对于父列表的偏移及范围等信息。对子列表的所有操作都是通过父列表来完成的。值得说明的是,因为SubList也是AbstractList的子类,因而也有一个modCount字段。在创建子列表时,modCount和父列表一致;以后每当通过子列表修改父列表时也都会保持一致。在调用子列表的方法时,类似于迭代器,首先也会通过checkForComodification方法确保父列表的结构没有发生改变,否则会抛出ConcurrentModificationException异常。 |
|
|
|
|
|