AbstractList源碼解析1 實現的方法2 兩種內部迭代器3 兩種內部類3 SubList 源碼分析4 RandomAccessSubList 源碼:AbstractList 作爲 Lis

它實現了 List 的一些位置相關操作(比如 get,set,add,remove),是第一個實現隨機訪問方法的集合類,但不支持添加和替換

AbstractCollection抽象類中要求子類必須實現兩個方法

  • iterator()
  • size()

AbstractList 實現了 iterator()方法:

但沒有實現 size() 方法 此外還提供了一個抽象方法 get()

因此子類必須要實現 get(), size()

如果子類想要能夠修改元素,還需要重寫 add(), set(), remove() 方法,否則會報拋UnsupportedOperationException

1 實現的方法

1.1 默認不支持的 add(), set(),remove()

1.2 indexOf(Object) 獲取指定對象 首次出現 的索引

  • L178 : 獲取 ListIterator,此時遊標位置爲 0

然後向後遍歷 每次調用 listIterator.next() 遊標 都會後移一位,當 listIterator.next() == o 時(即找到我們需要的的元素),遊標已經在 o 的後面,所以需要返回 遊標的 previousIndex().

1.3 lastIndexOf(Object)

獲取指定對象最後一次出現的位置

L203 : 獲取 ListIterator,此時遊標在最後一位 之後向前遍歷

1.4 clear(), removeRange(int, int),

全部/範圍 刪除元素:

傳入由子類實現的 size()

獲取 ListIterator 來進行迭代刪除

1.5 addAll

2 兩種內部迭代器

與其他集合實現類不同,AbstractList 內部已經提供了 Iterator, ListIterator 迭代器的實現類,分別爲 Itr, ListItr

2.1 Itr 源碼分析

private class Itr implements Iterator<E> {
    //遊標
    int cursor = 0;

    //上一次迭代到的元素的位置,每次使用完就會置爲 -1
    int lastRet = -1;

    //用來判斷是否發生併發操作的標示,如果這兩個值不一致,就會報錯
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size();
    }

    public E next() {
        //時刻檢查是否有併發修改操作
        checkForComodification();
        try {
            int i = cursor;
            //調用 子類實現的 get() 方法獲取元素
            E next = get(i);
            //有迭代操作後就會記錄上次迭代的位置
            lastRet = i;
            cursor = i + 1;
            return next;
        } catch (IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
        }
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            //調用需要子類實現的 remove()方法
            AbstractList.this.remove(lastRet);
            if (lastRet < cursor)
                cursor--;
            //刪除後 上次迭代的記錄就會置爲 -1
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
        }
    }

    //檢查是否有併發修改
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

可以看到 Itr 只是簡單實現了 Iterator 的 next, remove 方法

2.2 ListItr 源碼分析

//ListItr 是 Itr 的增強版
private class ListItr extends Itr implements ListIterator<E> {
    //多了個指定遊標位置的構造參數,怎麼都不檢查是否越界!
    ListItr(int index) {
        cursor = index;
    }

    //除了一開始都有前面元素
    public boolean hasPrevious() {
        return cursor != 0;
    }

    public E previous() {
        checkForComodification();
        try {
            //獲取遊標前面一位元素
            int i = cursor - 1;
            E previous = get(i);
            //爲什麼上次操作的位置是 遊標當前位置呢?哦,看錯了,遊標也前移了
            lastRet = cursor = i;
            return previous;
        } catch (IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
        }
    }

    //下一個元素的位置就是當前遊標所在位置
    public int nextIndex() {
        return cursor;
    }

    public int previousIndex() {
        return cursor-1;
    }

    public void set(E e) {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            //子類得檢查 lasRet 是否爲 -1
            AbstractList.this.set(lastRet, e);
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    public void add(E e) {
        checkForComodification();

        try {
            int i = cursor;
            AbstractList.this.add(i, e);
            //又置爲 -1 了
            lastRet = -1;
            cursor = i + 1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }
}

在 Itr 基礎上多了 向前 和 set 操作

3 兩種內部類

在 subList 方法中我們發現在切分 子序列時會分爲兩類,RandomAccess or not

3.1 RandomAccess

一個空接口,用來標識某個類是否支持 隨機訪問 一個支持隨機訪問的類明顯可以使用更加高效的算法

  • List 中支持隨機訪問最佳的例子就是ArrayList, 它的數據結構使得 get(), set(), add()等方法的時間複雜度都是 O(1)
  • 反例就是 LinkedList, 鏈表結構使得它不支持隨機訪問,只能順序訪問,因此在一些操作上性能略遜一籌

通常在操作一個 List 對象時,通常會判斷是否支持 隨機訪問,也就是是否爲 RandomAccess 的實例,從而使用不同的算法

比如遍歷,實現了 RandomAccess 的集合使用 get():

for (int i=0, n=list.size(); i < n; i++)
          list.get(i);

比用迭代器更快

  for (Iterator i=list.iterator(); i.hasNext(); )
      i.next();

實現了 RandomAccess 接口的類有: ArrayList, AttributeList, CopyOnWriteArrayList, Vector, Stack 等。

3 SubList 源碼分析

// AbstractList 的子類,表示父 List 的一部分
class SubList<E> extends AbstractList<E> {
    private final AbstractList<E> l;
    private final int offset;
    private int size;

//構造參數:
//list :父 List
//fromIndex : 從父 List 中開始的位置
//toIndex : 在父 List 中哪裏結束
SubList(AbstractList<E> list, int fromIndex, int toIndex) {
    if (fromIndex < 0)
        throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
    if (toIndex > list.size())
        throw new IndexOutOfBoundsException("toIndex = " + toIndex);
    if (fromIndex > toIndex)
        throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                           ") > toIndex(" + toIndex + ")");
    l = list;
    offset = fromIndex;
    size = toIndex - fromIndex;
    //和父類使用同一個 modCount
    this.modCount = l.modCount;
}

//使用父類的 set()
public E set(int index, E element) {
    rangeCheck(index);
    checkForComodification();
    return l.set(index+offset, element);
}

//使用父類的 get()
public E get(int index) {
    rangeCheck(index);
    checkForComodification();
    return l.get(index+offset);
}

//子 List 的大小
public int size() {
    checkForComodification();
    return size;
}

public void add(int index, E element) {
    rangeCheckForAdd(index);
    checkForComodification();
    //根據子 List 開始的位置,加上偏移量,直接在父 List 上進行添加
    l.add(index+offset, element);
    this.modCount = l.modCount;
    size++;
}

public E remove(int index) {
    rangeCheck(index);
    checkForComodification();
    //根據子 List 開始的位置,加上偏移量,直接在父 List 上進行刪除
    E result = l.remove(index+offset);
    this.modCount = l.modCount;
    size--;
    return result;
}

protected void removeRange(int fromIndex, int toIndex) {
    checkForComodification();
    //調用父類的 局部刪除
    l.removeRange(fromIndex+offset, toIndex+offset);
    this.modCount = l.modCount;
    size -= (toIndex-fromIndex);
}

public boolean addAll(Collection<? extends E> c) {
    return addAll(size, c);
}

public boolean addAll(int index, Collection<? extends E> c) {
    rangeCheckForAdd(index);
    int cSize = c.size();
    if (cSize==0)
        return false;

    checkForComodification();
    //還是使用的父類 addAll()
    l.addAll(offset+index, c);
    this.modCount = l.modCount;
    size += cSize;
    return true;
}

public Iterator<E> iterator() {
    return listIterator();
}

public ListIterator<E> listIterator(final int index) {
    checkForComodification();
    rangeCheckForAdd(index);

    //創建一個 匿名內部 ListIterator,指向的還是 父類的 listIterator
    return new ListIterator<E>() {
        private final ListIterator<E> i = l.listIterator(index+offset);

        public boolean hasNext() {
            return nextIndex() < size;
        }

        public E next() {
            if (hasNext())
                return i.next();
            else
                throw new NoSuchElementException();
        }

        public boolean hasPrevious() {
            return previousIndex() >= 0;
        }

        public E previous() {
            if (hasPrevious())
                return i.previous();
            else
                throw new NoSuchElementException();
        }

        public int nextIndex() {
            return i.nextIndex() - offset;
        }

        public int previousIndex() {
            return i.previousIndex() - offset;
        }

        public void remove() {
            i.remove();
            SubList.this.modCount = l.modCount;
            size--;
        }

        public void set(E e) {
            i.set(e);
        }

        public void add(E e) {
            i.add(e);
            SubList.this.modCount = l.modCount;
            size++;
        }
    };
}

public List<E> subList(int fromIndex, int toIndex) {
    return new SubList<>(this, fromIndex, toIndex);
}

private void rangeCheck(int index) {
    if (index < 0 || index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

private void rangeCheckForAdd(int index) {
    if (index < 0 || index > size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

private String outOfBoundsMsg(int index) {
    return "Index: "+index+", Size: "+size;
}

private void checkForComodification() {
    if (this.modCount != l.modCount)
        throw new ConcurrentModificationException();
}
}

總結

SubList 就是啃老族,雖然自立門戶,等到要幹活時,使用的都是父類的方法,父類的數據。 所以可以通過它來間接操作父 List

4 RandomAccessSubList 源碼:

  • RandomAccessSubList 只不過是在 SubList 之外加了個 RandomAccess 的標識,表明他可以支持隨機訪問而已

AbstractList 作爲 List 家族的中堅力量

  • 既實現了 List 的期望
  • 也繼承了 AbstractCollection 的傳統
  • 還創建了內部的迭代器 Itr, ListItr
  • 還有兩個內部子類 SubList 和 RandomAccessSublist;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章