SubList

  • 创建一个从原数组索引fromIndex到toIndex不包括(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
    34
    35
     public List<E> subList(int fromIndex, int toIndex) {
    subListRangeCheck(fromIndex, toIndex, size);
    return new SubList<>(this, fromIndex, toIndex);
    }
    private static class SubList<E> extends AbstractList<E> implements RandomAccess {
    private final ArrayList<E> root;
    private final SubList<E> parent;
    private final int offset; //偏移量
    private int size;

    Constructs a sublist of an arbitrary ArrayList.
    public SubList(ArrayList<E> root, int fromIndex, int toIndex) {
    this.root = root;
    this.parent = null;
    this.offset = fromIndex;
    this.size = toIndex - fromIndex;
    this.modCount = root.modCount;
    }

    Constructs a sublist of another SubList.
    private SubList(SubList<E> parent, int fromIndex, int toIndex) {
    this.root = parent.root;
    this.parent = parent;
    this.offset = parent.offset + fromIndex;
    this.size = toIndex - fromIndex;
    this.modCount = parent.modCount;
    }

    public E set(int index, E element);
    public E get(int index);
    public int size();
    public void add(int index, E element);
    public E remove(int index);
    protected void removeRange(int fromIndex, int toIndex);
    .......

E set(int index, E element)

  • 1
    2
    3
    4
    5
    6
    7
    public E set(int index, E element) {
    Objects.checkIndex(index, size);
    checkForComodification();
    E oldValue = root.elementData(offset + index);
    root.elementData[offset + index] = element;
    return oldValue;
    }

public E get(int index)

  • 1
    2
    3
    4
    5
    public E get(int index) {
    Objects.checkIndex(index, size);
    checkForComodification();
    return root.elementData(offset + index);
    }

add(int index, E element)

1
2
3
4
5
6
public void add(int index, E element) {
rangeCheckForAdd(index);
checkForComodification();
root.add(offset + index, element);
updateSizeAndModCount(1);
}

remove(int index)

1
2
3
4
5
6
7
public E remove(int index) {
Objects.checkIndex(index, size);
checkForComodification();
E result = root.remove(offset + index);
updateSizeAndModCount(-1);
return result;
}
1
2
3
4
5
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
root.removeRange(offset + fromIndex, offset + toIndex);
updateSizeAndModCount(fromIndex - toIndex);
}