【集合類】源碼解析之 List接口、AbstractList抽象類

List接口

存取順序一致,有索引,允許重複

類聲明

public interface List<E> extends Collection<E> 

特有方法

所有通過索引操作的方法都要注意其索引的範圍,否則容易導致發生 IndexOutOfBoundsException

void add(int index, E element); // 向指定索引處增加元素 0 <= index <= size
boolean addAll(int index, Collection<? extends E> c); // 向指定索引處增加集合中的所有元素 0 <= index <= size
E remove(int index); // 刪除指定索引位置的元素 0 <= index < size
E set(int index, E element); // 修改指定索引處的元素 0 <= index < size
E get(int index); // 獲取指定索引處的元素 0 <= index < size
int indexOf(Object o); // 獲取指定元素第一次出現的索引,若不存在則返回-1
int lastIndexOf(Object o); // 獲取指定元素最後一次出現的索引,若不存在則返回-1
List<E> subList(int fromIndex, int toIndex); // 返回集合中從fromIndex(含)到toIndex(不含)的視圖,與原集合會相互影響
ListIterator<E> listIterator(); // 返回listIterator hasPrevious()、previous()、add(E e);
ListIterator<E> listIterator(int index); // 從指定索引處開始返回listIterator 0 <= index <= size
// jdk1.8新增方法
default void sort(Comparator<? super E> c){} // 根據Comparator來排序數組
default void replaceAll(UnaryOperator<E> operator) {} // 將該列表的每個元素替換爲該運算符應用於該元素的結果

AbstractList抽象類

實現了 List 的部分方法,iteratorsize 沒有實現

類聲明

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>

主要字段

// 維護了集合被修改的次數
protected transient int modCount = 0;

方法實現

// 唯一的構造函數
protected AbstractList() {}
// 限定了add、set、remove操作, 由子類實現
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();}

// 獲取指定角標的元素,未實現
abstract public E get(int index);

// 從前往後找,獲取指定元素在集合中第一次出現的索引,若不存在則返回-1
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;
}

// 從後往前找,獲取指定元素在集合中第一次出現的索引,若不存在則返回-1
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;
}

// 在集合末尾添加元素, add由子類實現
public boolean add(E e) {
    add(size(), e);
    return true;
}

// 向指定索引處增加集合中的所有元素, add由子類實現
public boolean addAll(int index, Collection<? extends E> c) {
    // 索引檢查 index < 0 || index > size()
    rangeCheckForAdd(index);
    boolean modified = false;
    for (E e : c) {
        add(index++, e);
        modified = true;
    }
    return modified;
}

// 範圍刪除,包含 fromIndex,不包含 toIndex
protected void removeRange(int fromIndex, int toIndex) {
    ListIterator<E> it = listIterator(fromIndex);
    for (int i=0, n=toIndex-fromIndex; i<n; i++) {
        it.next();
        it.remove();
    }
}

// 調用 removeRange
public void clear() {
    removeRange(0, size());
}

// 獲取迭代器
public Iterator<E> iterator() {
    return new Itr();
}

// 獲取list迭代器
public ListIterator<E> listIterator() {
    return listIterator(0);
}

// 從指定索引獲取迭代器
public ListIterator<E> listIterator(final int index) {
    // 索引檢查 index < 0 || index > size()
    rangeCheckForAdd(index);
    return new ListItr(index);
}

// 截取集合,返回的集合與原集合相互影響
public List<E> subList(int fromIndex, int toIndex) {
    return (this instanceof RandomAccess ?
            new RandomAccessSubList<>(this, fromIndex, toIndex) :
            new SubList<>(this, fromIndex, toIndex));
}

// 兩個個內部類
private class Itr implements Iterator<E> {}
private class ListItr extends Itr implements ListIterator<E> {}
// 在AbstractList類下的兩個類,**不是內部類
class SubList<E> extends AbstractList<E> {}
class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {}

內部類 Itr

AbstractList通過使用兩個內部類 ItrListItr 實現集合的遍歷

private class Itr implements Iterator<E> {
        // 用來標識當前所要遍歷元素的下標
        int cursor = 0;

        // 用來記錄調用next調用後所指向的下標,調用remove後會重置爲-1
        int lastRet = -1;

       	// 用來標識最初的modCount(來至於外部類AbstractList),調用迭代器的修改方法會重新賦值
        int expectedModCount = modCount;

    	// 每次遍歷時add/remove都會修改modCount,若檢測到expectedModCount和modCount不一致就會拋異常
    	final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    	
    	// 判斷是否有下一個元素
        public boolean hasNext() {
            return cursor != size();
        }

    	// 獲取下一個元素,先檢測modCount是否被修改,獲取元素,修改lastRet和cursor
        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

    	// 刪除元素,刪除前必須調用next()方法,刪除的是當前元素也就是角標爲lastRet的元素
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                // 調用子類實現的remove方法刪除元素,並給cursor、lastRet和expectedModCount重新賦值
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }
    }

內部類 ListItr

ListItr 繼承了 Itr 實現了 ListIteratorListIterator 接口是對 Iterator 的擴展,使迭代器不僅能向後迭代也能向前迭代,還能獲取當前元素和將要遍歷元素的下標,也可對元素進行增、刪、改操作

private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            cursor = index;
        }

    	// 是否有前一個元素
        public boolean hasPrevious() {
            return cursor != 0;
        }

    	// 獲取前一個元素並修改cursor和lastRet
        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;
        }

    	// 調用子類實現的set方法修改元素並給並給expectedModCount重新賦值
        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();
            }
        }
        // 調用子類實現的add方法修改元素並給並給cursor、lastRet和expectedModCount重新賦值
        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();
            }
        }
    }

SubList

SubList 調用subList方法所創建的對象,所引用的還是原數組

class SubList<E> extends AbstractList<E> {
    // 用於存放原List的引用
    private final AbstractList<E> l;
    // 子List在原List中的開始位置
    private final int offset;
    // 子List的大小
    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;
    }
    
    // 下標檢測
    private void rangeCheck(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    // add下標檢測
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    // 修改檢測,判斷原集合中的modCount和SubList中的modCount是否相等
    private void checkForComodification() {
        if (this.modCount != l.modCount)
            throw new ConcurrentModificationException();
    }

	// 調用原集合的set方法 offset+index
    public E set(int index, E element) {
        rangeCheck(index);
        checkForComodification();
        return l.set(index+offset, element);
    }

    // 調用原集合的get方法 offset+index
    public E get(int index) {
        rangeCheck(index);
        checkForComodification();
        return l.get(index+offset);
    }

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

    // 調用原集合的add方法 offset+index,並修改this.mod和size
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        checkForComodification();
        l.add(index+offset, element);
        this.modCount = l.modCount;
        size++;
    }

    // 調用原集合的remove方法 offset+index,並修改this.mod和size
    public E remove(int index) {
        rangeCheck(index);
        checkForComodification();
        E result = l.remove(index+offset);
        this.modCount = l.modCount;
        size--;
        return result;
    }

    // 調用原集合的removeRange方法
    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();
        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實現
        return new ListIterator<E>() {
            // ...
        };
    }

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

    // 異常消息
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
}

RandomAccessSubList

RandomAccess 是一個標記接口,表明實現這個接口的 List 集合是支持快速隨機訪問,使用for循環遍歷效率會高於迭代器遍歷

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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章