1. 程式人生 > >Java集合類源碼解析:AbstractList

Java集合類源碼解析:AbstractList

tlist ica png 用途 access 可用 操作 map 支持

今天學習Java集合類中的一個抽象類,AbstractList

初識AbstractList

AbstractList 是一個抽象類,實現了List<E>接口,是隸屬於Java集合框架中的 根接口 Collection 的分支,由其衍生的很多子類因為擁有強大的容器性能而被廣泛應用,例如我們最為熟悉的ArrayList,這是它的類繼承結構圖:
技術分享圖片

特殊方法

AbstractList 雖然是抽象類,但其內部只有一個抽象方法 get():

abstract public E get(int index);

從字面上看這是獲取的方法,子類必須實現它,一般是作為獲取元素的用途,除此之外,如果子類要操作元素,還需要重寫 add(), set(), remove() 方法,因為 AbstractList 雖然定義了這幾個方法,但默認是不支持的,

public boolean add(E e) {
    add(size(), e);
    return true;
}
public void add(int index, E element) {
    throw new UnsupportedOperationException();
}
public E set(int index, E element) {
    throw new UnsupportedOperationException();
}
public E remove(int index) {
    throw new UnsupportedOperationException();
}

可以看到,在其默認實現裏,直接是拋出UnsupportedOperationException 異常的,這裏的處理跟AbstractMap 的 put() 方法有異曲同工之妙處,很大功能就是官方考慮到也許會有子類需要這些方法不可修改,需要修改的話直接重寫即可。

兩個叠代器實現類

AbstractList 中提供了兩個叠代器的實現類,默認實現了叠代器接口,實現了對元素的遍歷,它們就是Itr 和其子類 ListItr,分別來了解一下。

先看Itr類,Itr 實現了 Iterator 接口,重寫了 next() 和 remove() 方法,下面是它的源碼:

private class Itr implements Iterator<E> {
    //遊標
    int cursor;
    //最近叠代的元素位置,每次使用完默認置為-1
    int lastRet;
    //記錄容器被修改的次數,值不相等說明有並發操作
    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;
            return var2;
        } catch (IndexOutOfBoundsException var3) {
            this.checkForComodification();
            throw new NoSuchElementException();
        }
    }

    public void remove() {
        //還沒讀取元素就remove,報錯
        if (lastRet < 0) {
            throw new IllegalStateException();
        } else {
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor) {
                    --this.cursor;
                }
                //刪除後,把最後叠代的記錄位置置為-1
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException var2) {
                throw new ConcurrentModificationException();
            }
        }
    }
    //兩個值不一致,說明有並發操作,拋出異常
    final void checkForComodification() {
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
}

ListItr 是 Itr 的子類,在Itr 的基礎上增強了對元素的操作,多了指定索引的賦值,以及向前讀取,add 和 set 的方法。

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();
            }
        }
    }

兩個類的源碼還是比較簡單的,加了註釋相信大家也能看出大概的邏輯。使用上,AbstractList類中提供了兩個方法,返回的各自實現的接口類型對象:

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 還提供了兩個可以獲取對象索引的方法,分別是

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

public int indexOf(Object o) {
    //返回叠代器類,此時默認遊標位置是0
    ListIterator<E> it = listIterator();
    if (o==null) {
        //向後遍歷
        while (it.hasNext())
            //後面沒元素了,返回遊標前面元素的索引,這裏為什麽是返回前面索引呢?
            //因為在ListIterator接口中,每次調用next()遊標就會後移一位
            //所以,當找到對應元素時,遊標已經後移一位了,需要返回遊標的前一個索引。
            if (it.next()==null)
                return it.previousIndex();
    } else {
        while (it.hasNext())
            if (o.equals(it.next()))
                return it.previousIndex();
    }
    return -1;
}

lastIndexOf() :獲取指定對象最後一次出現的位置,原理和indexOf方法類似,只是改為後面向前

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;
}

兩個子類

AbstractList 提供了兩個子類,可用於切分集合序列,這兩個類是 SubListRandomAccessSubList ,SubList 的內部實現和 AbstractList 很相似,無非是傳遞了兩個變量,初識位置和結束位置來截取集合,具體原理就不做解析了,讀者們自己看看吧,也不難,貼一下部分源碼:

class SubList<E> extends AbstractList<E> {
    private final AbstractList<E> l;
    private final int offset;
    private int size;

    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;
        this.modCount = l.modCount;
    }

    public E set(int index, E element) {
        rangeCheck(index);
        checkForComodification();
        return l.set(index+offset, element);
    }
    ............
    ............
  }

RandomAccessSubList 是 SubList 的子類,內部實現直接沿用父類,只是實現了RandomAccess接口,這是源碼:

class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
        super(list, fromIndex, toIndex);
    }

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

不一樣的是,RandomAccessSubList 實現了一個接口RandomAccess,打開後發現是空的,沒有任何實現。

public interface RandomAccess {
}

它的作用是用於標識某個類是否支持 隨機訪問(隨機訪問,相對比“按順序訪問”)。一個支持隨機訪問的類明顯可以使用更加高效的算法。例如遍歷上,實現RandomAccess 接口的集合使用 get() 做叠代速度會更快,比起使用叠代器的話,

for (int i=0; i < list.size(); i++)
list.get(i);
 for (Iterator i=list.iterator(); i.hasNext();)
    i.next();

例如ArrayList 就是實現了這個接口,而關於該接口有如此功效的原因這裏暫且不做深入研究,日後有機會單獨寫一篇講解下。

最後

作為抽象類,AbstractList本身算是定義比較完善的結構體系了,繼承了它的衣缽的子類也擁有不俗的表現,在Java開發中被廣泛應用,有時間的話打算多寫幾篇關於它的子類,好了,關於 AbstractList 的知識就學到這裏了,睡覺了~

Java集合類源碼解析:AbstractList