java 集合框架-AbstractList

AbstractList 作爲具體List型具體類,實現AbstractCollection抽象類、繼承List接口,實現了部分方法
- indexOf
- lastIndexOf
- subList
- addAll
- iterator
- listIterator
- equals
- hashCode

下面源碼分析一些較複雜的方法實現

一、實現List的接口方法

indexOf、lastIndexOf、subList

    public int indexOf(Object o) {
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return it.previousIndex();
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }

indexOf 方法使用List特有的ListIterator實現,在遍歷判斷中,使用List雙向的特性,返回index,不需要每次記錄index;
有關listIterator的詳情,後面分析

    public int lastIndexOf(Object o) {
        ListIterator<E> it = listIterator(size());
        if (o==null) {
            while (it.hasPrevious())
                if (it.previous()==null)
                    return it.nextIndex();
        } else {
            while (it.hasPrevious())
                if (o.equals(it.previous()))
                    return it.nextIndex();
        }
        return -1;
    }

lastIndexOf 就將ListIterator 雙向遍歷的特性用的更加完成,直接反向遍歷查詢;

二、迭代器實現

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

    public ListIterator<E> listIterator() {
        return listIterator(0);
    }

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

        return new ListItr(index);
    }

前面兩篇的描述中,都強調迭代器的重要性,在AbstractList就可以看到它的實現了:

    private class Itr implements Iterator<E> {
        /**
         * Index of element to be returned by subsequent call to next.
         */
        int cursor = 0; //遊標,表示當前迭代處於的位置;初始爲0,總是從第一個元素開始

        /**
         * Index of element returned by most recent call to next or
         * previous.  Reset to -1 if this element is deleted by a call
         * to remove.
         */
        int lastRet = -1; //表示當前迭代處於位置的前一個下標,remove移除元素就是這個下標對應的元素,移除後恢復爲-1,表示remove只能在每次next方法後調用一次

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        int expectedModCount = modCount;//這個整型數用來保證迭代時,集合沒有發生併發的修改

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

        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i; //記錄位置
                cursor = i + 1; //每次next,遊標後移一位
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (lastRet < 0) //不可在next方法前、或一次next方法後兩次調用
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() { //該方法檢測是否發生了併發修改
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

迭代器的實現並不複雜,唯有併發修改的快速失敗(ConcurrentModificationException),只從上面的源碼還看不出來,需要知道modCount值的變化,從迭代器的remove方法可以猜測到,在對集合修改時,這個值是會發送變化,當處於迭代時,其他線程修改集合導致這個值改變,那麼可以檢測到併發修改;

我們來看下這個屬性在AbstractList中的定義:

    /**
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     *
     * <p>This field is used by the iterator and list iterator implementation
     * returned by the {@code iterator} and {@code listIterator} methods.
     * If the value of this field changes unexpectedly, the iterator (or list
     * iterator) will throw a {@code ConcurrentModificationException} in
     * response to the {@code next}, {@code remove}, {@code previous},
     * {@code set} or {@code add} operations.  This provides
     * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
     * the face of concurrent modification during iteration.
     *
     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
     * wishes to provide fail-fast iterators (and list iterators), then it
     * merely has to increment this field in its {@code add(int, E)} and
     * {@code remove(int)} methods (and any other methods that it overrides
     * that result in structural modifications to the list).  A single call to
     * {@code add(int, E)} or {@code remove(int)} must add no more than
     * one to this field, or the iterators (and list iterators) will throw
     * bogus {@code ConcurrentModificationExceptions}.  If an implementation
     * does not wish to provide fail-fast iterators, this field may be
     * ignored.
     */
    protected transient int modCount = 0;

註釋大概說明三個點,和我們猜測的一致:
- 記錄在結構上修改集合的次數
- 這個字段被用於迭代器,用於提供併發修改的快速失敗機制
- 子類可以選擇是否使用這個機制,實現只需要在修改結構的方法遞增這個值即可;不實現直接忽略該值

接下來再看下ListIterator:

    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 {
                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);
                lastRet = -1;
                cursor = i + 1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

可以看出,實現和Itr很相似,增加幾個特性:
- 允許指定下標開始迭代
- 支持雙向迭代
- 允許修改當前下標元素
- 允許在當前下標添加元素

Object 聲明的三個常需實現方法:toString、equals、hashCode;AbstractCollection已經實現了toString,
AbstractList實現了剩下的兩個方法:

    public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }

    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;

        ListIterator<E> e1 = listIterator();
        ListIterator e2 = ((List) o).listIterator();
        while (e1.hasNext() && e2.hasNext()) {
            E o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
    }

兩個list相等的條件是類型一樣、size一樣、每個元素對應相等;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章