Java基礎之Collections框架List接口實現類ArrayList及其源碼分析

Java基礎之Collections框架List接口實現類ArrayList及其源碼分析


List接口的可調整大小的數組實現。 實現所有可選的列表操作,並允許所有元素,包括null。 除了實現List接口之外,此類還提供一些方法來操縱內部用於存儲列表的數組的大小。
size,isEmpty,get,set,iterator和listIterator操作在恆定時間內運行。 加法運算以固定的固定時間運行,即,添加n個元素需要O(n)時間。 所有其他操作均以線性時間運行.
每個ArrayList實例都有一個容量。 容量是用於在列表中存儲元素的數組的大小。 它總是至少與列表大小一樣大。 將元素添加到ArrayList時,其容量會自動增長。
應用程序可以使用ensuresureCapacity操作在添加大量元素之前增加ArrayList實例的容量。 這可以減少增量重新分配的數量。

ArrayList的簡單使用

List<String> list = new ArrayList<String>();
//新增元素
list.add("tony");
list.add("projects");
System.out.println(list.toString());
//移除指定元素
list.remove("projects");
System.out.println(list.toString());
Set<String> setTemp = new HashSet<String>();
setTemp.add("projects");
setTemp.add("tony");
//添加置頂集合中的所有元素
list.addAll(setTemp);
System.out.println(list.toString());
//獲取指定元素的索引
System.out.println(list.indexOf("tony"));
//獲取指定元素最後一次的索引
System.out.println(list.lastIndexOf("tony"));
//判斷是否包含指定元素
System.out.println(list.contains("tony"));
//獲取指定索引下的元素
System.out.println(list.get(0));
//進行排序
Collections.sort(list);;
System.out.println(list.toString());
......

ArrayList源碼分析

public class ArrayList<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
	//序列化值
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 默認的容量大小爲10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 用於空實例的共享空數組實例.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     共享的空數組實例,用於默認大小的空實例。 我們將此與EMPTY_ELEMENTDATA區別開來,知道何時需要擴充容量進行添加第一個元素
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 存儲ArrayList元素的數組緩衝區
     * ArrayList的容量是此數組緩衝區的長度.任何具有elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空ArrayList
     * 添加第一個元素時,將擴展爲DEFAULT_CAPACITY
     */
    transient Object[] elementData; //非私有以簡化嵌套類訪問

    /**
    ArrayList的大小
     */
    private int size;

    /**
     * 構造一個具有指定初始容量的空列表.
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
        	//大於0就創建一個默認的容量列表
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
        	//等於0的時候創建一個空的列表
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
        	//容量小於0的情況將拋出異常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * 構造一個初始容量爲10的空列表
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     構造一個包含指定元素的列表集合,按集合的返回順序迭代器。
     */
    public ArrayList(Collection<? extends E> c) {
    	//將傳入的集合轉變爲數組
        elementData = c.toArray(); 
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            //校驗相關的類型
            if (elementData.getClass() != Object[].class)
            	//進行數組的copy
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 集合爲空就創建一個空的數組
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     將該ArrayList實例的容量修改爲列表的當前大小。 應用程序可以使用此操作來最小化ArrayList 實例的存儲。
     */
    public void trimToSize() {
        modCount++;
        //元素個數小於數組的大小,說明可以調整
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    /**
    增加此ArrayList 實例的容量,如果必要,以確保它至少可以容納數量的元素由最小容量參數指定。
     */
    public void ensureCapacity(int minCapacity) {
   		//如果不是空的數組
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // 任何大小(如果不是默認元素表)
            ? 0
            // 大於默認值的默認空表。 它應該已經是默認大小。
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }
	//確保容量
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 要分配的最大數組大小
     * 一些虛擬機在數組中保留一些標題字
    嘗試分配更大的數組可能會導致OutOfMemoryError:請求的數組大小超出了VM限制
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
   增加容量以確保它至少可以容納最小容量參數指定的元素數。
     */
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        //等於原來元素組的大小 + 原來元素組的大小 / 2
        int newCapacity = oldCapacity + (oldCapacity >> 1);  
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity通常接近大小,進行數據copy操作
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    /**
     * 返回列表中元素的數量
     */
    public int size() {
        return size;
    }

    /**
    返回list是否爲空
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     返回數組中是否包含指定元素
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * 返回指定元素首次出現的索引
     */
    public int indexOf(Object o) {
        if (o == null) {
        	//通過遍歷進行查詢元素
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
        	//通過遍歷進行查詢元素
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;  //如果不存在就返回-1
    }

    /**
    返回指定元素最後一次出現的索引
     */
    public int lastIndexOf(Object o) {
        if (o == null) {
       		 //從數組尾部開始遍歷
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
        	//從數組尾部開始遍歷
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;  //如果不存在就返回-1
    }

    /**
     * 返回此ArrayList實例的淺表副本
     */
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

    /**
    返回一個包含此列表中所有元素的數按正確的順序
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     返回指定類型的數組
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // 創建一個新的a的運行時類型數組
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    @SuppressWarnings("unchecked")
    E elementData(int index) {
    	//獲取數組指定索引位置的元素
        return (E) elementData[index];
    }

    /**
     * 返回此列表中指定位置的元素
     */
    public E get(int index) {
        rangeCheck(index)
        return elementData(index);
    }

    /**
     將列表中指定位置的元素替換爲指定的元素,並返回修改之前的數據
     */
    public E set(int index, E element) {
        rangeCheck(index);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /**
     將指定的元素追加到此列表的末尾
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 增加modCount
        elementData[size++] = e;
        return true;
    }

    /**
    將指定的元素插入此位置中的指定位置清單。 移動當前在該位置的元素(如果有),然後右邊的任何後續元素(將其索引加一個)。
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1);  
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

    /**
     刪除此列表中指定位置的元素。將所有後續元素向左移動(從其元素中減去一個索引)。
     */
    public E remove(int index) {
        rangeCheck(index);
        modCount++;
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // 這是爲null,讓GC回收
        return oldValue;
    }

    /**
     從列表中刪除第一次出現的指定元素
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;   //如果不存在就返回false
    }

    /*
    私有刪除方法,跳過邊界檢查並且不返回刪除的值。
     */
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // 這是爲null,讓GC回收
    }

    /**
    移除列表中的所有元素
     */
    public void clear() {
        modCount++;
        // 這是爲null,讓GC回收
        for (int i = 0; i < size; i++)
            elementData[i] = null; //將所有元素設置爲null 
        size = 0;
    }

    /**
     將指定集合中的所有元素追加到此列表,由它們按順序返回指定集合的​​Iterator
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        //進行數組擴容
        ensureCapacityInternal(size + numNew);  
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     將指定集合中的所有元素插入此對象列表,從指定位置開始
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        Object[] a = c.toArray();
        int numNew = a.length;
         //進行數組擴容
        ensureCapacityInternal(size + numNew);  
        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
    從該列表中刪除索引在之間的所有元素 fromIndex(含)和toIndex(不含)
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    /**
     * 檢查給定索引是否在範圍內。
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * add和addAll使用的rangeCheck版本
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
    構造一個IndexOutOfBoundsException詳細消息
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     從此列表中刪除包含在其中的所有元素指定的集合。
     */
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    /**
     僅保留此列表中包含在指定的集合
     */
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }
	/**
	批量移除元素,complement是否保留指定列表的元素刪除其他的
	*/
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // 保留與AbstractCollection的行爲兼容性
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // 這是爲null,讓GC回收
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

    /**
    序列化list列表
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // 寫出元素計數以及任何隱藏的內容
        int expectedModCount = modCount;
        s.defaultWriteObject();
        // 寫出大小作爲與clone()行爲兼容的容量
        s.writeInt(size);

        //按照正確的順序寫出所有元素。
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
  	反序列化
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA; //設置一個空的數組
        // 讀取大小和任何隱藏的東西
        s.defaultReadObject();
        // 讀取容量
        s.readInt(); // ignored
        if (size > 0) {
            // 像clone()一樣,根據大小而不是容量分配數組
            ensureCapacityInternal(size);
            Object[] a = elementData;
            // 按適當的順序讀取所有元素
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

    /**
    返回此列表中元素的列表迭代器(正確序列),從列表中的指定位置開始。
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
    返回此列表中元素的列表迭代器(正確序列)。
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 以適當的順序返回此列表中元素的迭代器
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * 返回一個迭代器,優化之後的版本
     */
    private class Itr implements Iterator<E> {
        int cursor;       // 下一個要返回的元素的索引
        int lastRet = -1; // 最後返回元素的索引;如果沒有 爲-1
        int expectedModCount = modCount;
		//返回是是否有寫一個元素,如果下一個的索引等於數組的大小值,則返回false
        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
        	//檢查expectedModCount
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
		//進行remove的時候需要調用next,不然會拋出異常,由上面的方法可以給lastRet進行賦值
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            //檢查expectedModCount
            checkForComodification();
            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

		//進行for流的遍歷Consumer<? super E> consumer
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // 在迭代結束時更新一次,以減少堆寫入流量
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }
		//檢查expectedModCount
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }
		//判斷是否有上一個元素
        public boolean hasPrevious() {
            return cursor != 0;
        }
		//獲取下一個的索引
        public int nextIndex() {
            return cursor;
        }
        //獲取前一個索引
        public int previousIndex() {
            return cursor - 1;
        }
		//獲取當前索引的上一個元素
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }
		//替換指定索引位置的值爲e
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
		//添加一個元素(當前元素下標之後)
        public void add(E e) {
            checkForComodification();
            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * 返回指定位置之間此列表部分的視圖fromIndex(含)和toIndex(不含)
     */
    public List<E> subList(int fromIndex, int toIndex) {
    	//檢查相關索引的合法性
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    } 
      
    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
    返回Spliterator
     */
    @Override
    public Spliterator<E> spliterator() {
        return new ArrayListSpliterator<>(this, 0, -1, 0);
    }

    /**基於索引的二分之一,延遲初始化的Spliterator */
    static final class ArrayListSpliterator<E> implements Spliterator<E> {

        /*
         * 如果ArrayList是不可變的,或結構上不可變的  我們可以實現他們的分離器與Arrays.spliterator。相反,我們檢測到遍歷過程中的干擾犧牲很多性能. 我們主要依靠modCounts。 
         */
        private final ArrayList<E> list;
        private int index; // 當前索引,在提前/拆分時修改
        private int fence; //-1,直到使用; 然後是最後一個索引
        private int expectedModCount; //設置fence時初始化

        /** 創建覆蓋給定範圍的新分離器 */
        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                             int expectedModCount) {
            this.list = list;
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        private int getFence() { // 初始化 fence
            int hi; //一個專門的變體出現在forEach方法中
            ArrayList<E> lst;
            if ((hi = fence) < 0) {
                if ((lst = list) == null)
                    hi = fence = 0;
                else {
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        public ArrayListSpliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null : // 除非太小,否則將範圍分成兩半
                new ArrayListSpliterator<E>(list, lo, index = mid,
                                            expectedModCount);
        }

        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            if (i < hi) {
                index = i + 1;
                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi, mc; // hoist accesses and checks from loop
            ArrayList<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null && (a = lst.elementData) != null) {
                if ((hi = fence) < 0) {
                    mc = lst.modCount;
                    hi = lst.size;
                }
                else
                    mc = expectedModCount;
                if ((i = index) >= 0 && (index = hi) <= a.length) {
                    for (; i < hi; ++i) {
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (lst.modCount == mc)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }
		//返回預估值
        public long estimateSize() {
            return (long) (getFence() - index);
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
    @Override
    public boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // 找出要刪除的元素在此階段從篩選謂詞引發的任何異常將使集合保持不變
        int removeCount = 0;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // 將剩餘的剩餘元素移到已刪除元素剩餘的空間上
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

	//替換所有元素,接受一個函數式接口
	//UnaryOperator表示對單個操作數產生的運算結果與操作數相同的類型。 這是{@code Function}的專門用於操作數和結果爲相同類型的情況。
    @Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

	//進行排序指定比較器
    @Override
    @SuppressWarnings("unchecked")
    public void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        //expectedModCount檢查對比
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }
}

上面的代碼解釋了相關的list的分離器和特殊的迭代器.我們從上面的代碼可以看出,ArrayList的操作其實是對Object數組的操作.會初始化Object的數組。同時操作會不斷的檢查expectedModCount.同時添加多個和相應的移除多個是通過Arrays類和System類處理數組的。並且調用迭代器的remove方法的時候,需要lastRet不能爲-1,所以需要調用迭代器的next進行給lastRet設置值,不然會拋出異常。(默認lastRet爲-1,小於0)

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