1. 程式人生 > >Java 集合深入理解(6):AbstractList

Java 集合深入理解(6):AbstractList

今天心情比天藍,來學學 AbstractList 吧!

這裡寫圖片描述

什麼是 AbstractList

這裡寫圖片描述

AbstractList 繼承自 AbstractCollection 抽象類,實現了 List 介面 ,是 ArrayList 和 AbstractSequentiaList 的父類。

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

AbstractCollection 抽象類 中我們知道,AbstractCollection 要求子類必須實現兩個方法: iterator() 和 size()。 AbstractList 實現了 iterator()方法:

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

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

public abstract E get(int location);

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

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

實現的方法

1.預設不支援的 add(), set(),remove():

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

2.indexOf(Object) 獲取指定物件 首次出現 的索引:

public int indexOf(Object o) {
    //獲取 ListIterator,此時遊標位置為 0 
    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;
}

ListIterator 中我們介紹了 遊標 的概念,每次呼叫 listIterator.next() 方法 遊標 都會後移一位,當 listIterator.next() == o 時(即找到我們需要的的元素),遊標已經在 o 的後面,所以需要返回 遊標的 previousIndex().

3.lastIndexOf(Object) 獲取指定物件最後一次出現的位置:

public int lastIndexOf(Object o) {
    //獲取 ListIterator,此時遊標在最後一位
    ListIterator<E> it = listIterator(size());
    if (o==null) {
        //向前遍歷
        while (it.hasPrevious())
            if (it.previous()==null)
                //返回 it.nextIndex() 原因類似 2
                return it.nextIndex();
    } else {
        while (it.hasPrevious())
            if (o.equals(it.previous()))
                return it.nextIndex();
    }
    return -1;
}

4.clear(), removeRange(int, int), 全部/範圍 刪除元素:

public void clear() {
    //傳入由子類實現的 size()
    removeRange(0, size());
}

protected void removeRange(int fromIndex, int toIndex) {
    //獲取 ListIterator 來進行迭代刪除
    ListIterator<E> it = listIterator(fromIndex);
    for (int i=0, n=toIndex-fromIndex; i<n; i++) {
        it.next();
        it.remove();
    }
}

5.addAll(int,Collection

兩種內部迭代器

與其他集合實現類不同,AbstractList 內部已經提供了 Iterator, ListIterator 迭代器的實現類,分別為 Itr, ListItr, 不需要我們去幫他實現。

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 方法。

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

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

兩種內部類

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

public List<E> subList(int fromIndex, int toIndex) {
    return (this instanceof RandomAccess ?
            new RandomAccessSubList<>(this, fromIndex, toIndex) :
            new SubList<>(this, fromIndex, toIndex));
}

RandomAccess

public interface RandomAccess {
}

RandomAccess 是一個空的介面,它用來標識某個類是否支援 隨機訪問(隨機訪問,相對比“按順序訪問”)。一個支援隨機訪問的類明顯可以使用更加高效的演算法。

List 中支援隨機訪問最佳的例子就是 ArrayList, 它的資料結構使得 get(), set(), add()等方法的時間複雜度都是 O(1);

反例就是 LinkedList, 連結串列結構使得它不支援隨機訪問,只能按序訪問,因此在一些操作上效能略遜一籌。

通常在操作一個 List 物件時,通常會判斷是否支援 隨機訪問,也就是* 是否為 RandomAccess 的例項*,從而使用不同的演算法。

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

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

比用迭代器更快

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

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

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。

RandomAccessSubList 原始碼:

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 只不過是在 SubList 之外加了個 RandomAccess 的標識,表明他可以支援隨機訪問而已,別無他爾。

總結:

這裡寫圖片描述

AbstractList 作為 List 家族的中堅力量

  • 既實現了 List 的期望
  • 也繼承了 AbstractCollection 的傳統
  • 還建立了內部的迭代器 Itr, ListItr
  • 還有兩個內部子類 SubList 和 RandomAccessSublist;

百廢俱興,AbstractList 博採眾長,制定了 List 家族的家規,List 家族基礎已經搭建的差不多了。

List 家族在 AbstractList 的指導下出了幾個英豪,成為了 Java 世界的棟樑之才,具體細節,我們下回再續。