天天看點

List接口 — Vector類源碼分析

Vector的源碼了解起來不難,Vector是由數組來實作的,對于增删改查也是數組的相關操作

源碼中隻保留了重要的代碼,删去了部分代碼(包的導入與英文注釋)

Vector類的聲明​​1​​

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable      

繼承了AbstractList抽象類(實作了List接口,擁有增删查改等方法);Vector 實作了RandmoAccess接口,即提供了随機通路功能。RandmoAccess是java中用來被List實作,為List提供快速通路功能的。在Vector中,我們即可以通過元素的序号快速擷取元素對象;這就是快速随機通路。

Vector 實作了Cloneable接口,即實作clone()函數。它能被克隆。

Vector類的字段

// 核心: 用來儲存資料的數組,類型為Object,是以可以存儲任意類型的資料
    protected Object[] elementData;
    // 核心: elementData數組的實際容量
    protected int elementCount;
    // 添加資料若需要擴容時的容量自動增加的一個量
    protected int capacityIncrement;
    // 官方解釋:使用JDK 1.0.2中的序列化版本uid實作互操作性 
    private static final long serialVersionUID = -2767605614048989439L;

    // 并未在Vector類中出現,繼承了父類AbstractList中的字段
    // 已從結構上修改 此清單的次數。
    // 從結構上修改是指更改清單的大小,或者打亂清單,進而使正在進行的疊代産生錯誤的結果。
    protected transient int modCount = 0;      

Vector類的四個構造函數

/**
    * 使用指定的初始通量和容量增量構造一個空的向量
    * 
    * @param initialCapacity 向量的初始容量
    * @param capacityIncrement 當向量溢出時,容量增加的數量
    */
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        // 自己在構造方法時一定要考慮這種特殊情況,來防止意外發生
        if (initialCapacity < 0) 
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        // 直接new一個Object類型數組,數組大小即為第一個入參的值
        this.elementData = new Object[initialCapacity]; 
        // 設定容量增長的大小
        this.capacityIncrement = capacityIncrement;
    }

 
    public Vector(int initialCapacity) {
        this(initialCapacity, 0); // 調用上一個構造函數,隻是把向量增量設定為1
    }


    public Vector() {
        this(10); // 調用上一個構造函數,對于new一個無參的Vector對象,預設設定數組大小為10
    }

    /**
    * 将集合元素按照順序複制到elementData數組中
    * 
    * @param Collection<? extends E> c 要複制的集合
    */
    public Vector(Collection<? extends E> c) {
        // 擷取集合c轉換為數組後指派給elementData
        elementData = c.toArray(); 
        // 設定數組的長度
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }      

Vector類方法的輔助方法(不可調用)

/** 當添加元素時會先調用這個方法,來确認容量的大小是否能夠繼續添加元素
   *
   * @param minCapacity 這個參數的值為 elementCount + 1,即數組的元素個數+1
   */
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

   // 若數組元素添加一個元素後的大小比數組的長度 大時,那麼就需要增加數組的長度,否則将會出現數組越界異常
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

   // 要配置設定的數組的最大大小
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

   // 增加數組的長度
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length; // 原數組的長度
        // 若沒有設定向量增長系數(即new對象時沒有調用第一個構造函數),那麼預設增加為該數組兩倍的大小
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ? // 是否設定了向量增長系數
                                         capacityIncrement : oldCapacity);
      // 假設newCapacity的大小為2*oldCapacity即兩倍的數組的長度.
      // 若兩倍數組長度大于數組長度+1,那麼該數組大小直接為數組長度加1的大小,并不會增加無用的數組長度.
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity; 
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        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;
    }      

Vector類的API

// 将Vector的元素全部拷貝到anArray數組中
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }

   // 若數組的大小比實際的元素的個數大,将會通過複制的方式來賦給一個隻包含元素的數組
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }
 
   // 設定此向量的大小
    public synchronized void setSize(int newSize) {
        modCount++;
        // 新大小 > 目前大小,會建立一個新的長度的數組
        if (newSize > elementCount) {
            ensureCapacityHelper(newSize);
        } else { // 如果新大小小于目前大小,則丢棄索引 newSize 處及其之後的所有項
            for (int i = newSize ; i < elementCount ; i++) {
                elementData[i] = null;
            }
        }
        // 數組的大小等于設定的新大小
        elementCount = newSize;
    }

   // 傳回數組的長度
    public synchronized int capacity() {
        return elementData.length;
    }

      // 傳回數組的實際大小(即數組元素的個數)
    public synchronized int size() {
        return elementCount;
    }

    // 判斷數組是否含有元素                            
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }

   // 傳回此向量的元件的枚舉。
   // 傳回的枚舉對象将生成該向量中的所有項。
   // 生成的第一項是索引0處的項,然後是索引1處的項,依此類推。       
    public Enumeration<E> elements() {
      // 使用匿名内部類實作Enumeration
        return new Enumeration<E>() {
            int count = 0;
         // 下一個是否還有元素
            public boolean hasMoreElements() {
                return count < elementCount;
            }
         // 傳回該元素,并且count+1
            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

    // 是否包含元素o
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    // 傳回元素o的索引
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

   /** 
   * 第index項開始,傳回元素o在向量中第一次出現的角标
   *
   * @param o 要搜尋的元素
   * @param index 搜尋開始的索引
   */
    public synchronized int indexOf(Object o, int index) {
        if (o == null) { // 若沒有這步操作,将會報錯 
                   // Exception in thread "main" java.lang.NullPointerException  
            for (int i = index ; i < elementCount ; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index ; i < elementCount ; i++)    
                // 注意重寫equals()方法               
                if (o.equals(elementData[i])) 
                    return i;
        }
        // 未找到元素,則傳回-1
        return -1;
    }

   // 傳回此向量中最後一次出現的指定元素的索引
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount-1);
    }

   // 從 index 處逆向搜尋,傳回此向量中最後一次出現的指定元素的索引
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

        if (o == null) {
            for (int i = index; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    // 傳回角标為index的向量的值
    public synchronized E elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }

        return elementData(index);
    }

    // 傳回向量的第一個元素(位于索引0)
    public synchronized E firstElement() {
      // 元素個數為0(即沒有為空),則抛出異常 : 枚舉中沒有更多的元素
        if (elementCount == 0) { 
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    // 傳回向量的最後一個元素(位于索引elementData.size()-1)
    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }

   /**
   * 将此向量指定 index 處的元件設定為指定的對象。
   *
   * @param obj 設定的元素
   * @param index 指定的索引
   */
    public synchronized void setElementAt(E obj, int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        elementData[index] = obj;
    }

    // 删除指定索引處的值
    public synchronized void removeElementAt(int index) {
        modCount++;
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        // j : 索引處之後元素的個數 
        int j = elementCount - index - 1;
        // 如果要删除的索引之後有值那麼就把之後的值全部向前移一位
        if (j > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, j);
        }
        // 元素數量減1
        elementCount--;
        // 将删除的元素調整到向量末尾後設定為null
        elementData[elementCount] = null; /* to let gc do its work */
    }

      // 在指定索引處插入指定對象
    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index
                                                     + " > " + elementCount);
        }
        // 插入之前先檢查向量是否能容下将要插入的對象
        ensureCapacityHelper(elementCount + 1);
        // 将指定索引之後的元素都向後移1位
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        elementData[index] = obj;
        elementCount++;
    }

   // 在向量末尾添加元素obj      
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        // 先将末尾設定為obj後,元素個數加1(很巧妙)
        elementData[elementCount++] = obj;
    }

      // 從此向量中移除變量的第一個(索引最小的)比對項
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

      // 移除向量所有元素,并将其大小設定為0
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

   // 重寫了父類clone()方法
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
            // 重新new一個對象,進而不影響原向量
            Vector<E> v = (Vector<E>) super.clone();
            v.elementData = Arrays.copyOf(elementData, elementCount);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) { 
         // 如果對象的類不支援 Cloneable 接口,則重寫 clone 方法的子類也會抛出此異常,
         // 以訓示無法複制某個執行個體
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

      
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

   @SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
      // 當建立的數組的長度小于向量集的大小,則直接通過Arrays方法進行複制
        // 但這樣會建立一個數組T[]
        if (a.length < elementCount)               
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass()); 
      // 建立的數組長度大于向量集的大小
        System.arraycopy(elementData, 0, a, 0, elementCount); // 先将向量集中的元素複制到建立的數組中
      // 大于向量集的元素将指派為null
        if (a.length > elementCount) 
            a[elementCount] = null;
      // 若建立的數組的大小剛好和向量集大小相同,則直接傳回複制好的數組a.
        return a; 
    }
   
 
    // 輔助方法
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

   // 傳回向量中指定位置的元素
    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

   // 用指定的元素替換此向量中指定位置處的元素
    public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
      
        E oldValue = elementData(index);
        elementData[index] = element;
        // 傳回以前指定位置的索引
        return oldValue;
    }

      // 将指定元素添加到此向量的末尾(與addElement(E obj)方法類似
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

   // 移除此向量中指定元素的第一個比對項
    public boolean remove(Object o) {
        return removeElement(o);
    }

   // 在此向量的指定位置插入指定的元素
    public void add(int index, E element) {
        insertElementAt(element, index);
    }

      // 移除此向量中指定位置的元素
    public synchronized E remove(int index) {
        modCount++;
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        E oldValue = elementData(index);

        int numMoved = elementCount - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--elementCount] = null; // Let gc do its work

        return oldValue;
    }

      // 從此向量中移除所有元素
    public void clear() {
        removeAllElements();
    }

   // 如果此向量包含指定 Collection 中的所有元素,則傳回 true(效率很低)
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

   // 将指定 Collection 中的所有元素添加到此向量的末尾
   // 按照指定 collection 的疊代器所傳回的順序添加這些元素
    public synchronized boolean addAll(Collection<? extends E> c) {
        modCount++;
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);
        System.arraycopy(a, 0, elementData, elementCount, numNew);
        elementCount += numNew;
        return numNew != 0;
    }

   // 從此向量中移除包含在指定 Collection 中的所有元素
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

   // 在此向量中僅保留包含在指定 Collection 中的元素(相當于:移除向量中不在Collection中的元素
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

   // 在指定位置将指定 Collection 中的所有元素插入到此向量中
    public synchronized boolean addAll(int index, Collection<? extends E> c) {
        modCount++;
        if (index < 0 || index > elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);

        int numMoved = elementCount - index;
        // 将索引之後的元素向右移動(索引+集合的個數)位(即空出位置來讓集合的元素插入)
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
      // 複制集合中的元素到向量已經留好的位置
        System.arraycopy(a, 0, elementData, index, numNew);
        elementCount += numNew;
        return numNew != 0;
    }

    // 當且僅當指定的對象也是一個 List、兩個 List 大小相同,
    // 并且其中所有對應的元素對都相等 時才傳回 true
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }

   // 傳回此向量的哈希碼值
    public synchronized int hashCode() {
        return super.hashCode();
    }

   // 傳回此向量的字元串表示形式,其中包含每個元素的 String 表示形式
    public synchronized String toString() {
        return super.toString();
    }

      // 傳回此 List 的部分視圖,元素範圍為從 fromIndex(包括)到 toIndex(不包括).
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
                                            this);
    }

    // 删除向量中fromIndex(包括)到toIndex(不包括)的元素
    protected synchronized void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = elementCount - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // Let gc do its work
        int newElementCount = elementCount - (toIndex-fromIndex);
        while (elementCount != newElementCount)
            elementData[--elementCount] = null;
    }

   // 從流(即反序列化)加載代碼向量執行個體。此方法執行檢查以確定字段的一緻性
    private void readObject(ObjectInputStream in)
            throws IOException, ClassNotFoundException {
        ObjectInputStream.GetField gfields = in.readFields();
        int count = gfields.get("elementCount", 0);
        Object[] data = (Object[])gfields.get("elementData", null);
        if (count < 0 || data == null || count > data.length) {
            throw new StreamCorruptedException("Inconsistent vector internals");
        }
        elementCount = count;
        elementData = data.clone();
    }

      // 将代碼向量執行個體的狀态儲存到流(即序列化它)。此方法執行同步以確定序列化資料的一緻性。
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        final java.io.ObjectOutputStream.PutField fields = s.putFields();
        final Object[] data;
        synchronized (this) {
            fields.put("capacityIncrement", capacityIncrement);
            fields.put("elementCount", elementCount);
            data = elementData.clone();
        }
        fields.put("elementData", data);
        s.writeFields();
    }

    // 從清單中的指定位置開始,傳回清單中的元素(按正确順序)的清單疊代器。
    public synchronized ListIterator<E> listIterator(int index) {
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

   // 傳回清單中的清單疊代器(按适當的順序)。
    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

      // 以正确的順序傳回該清單中的元素的疊代器。
    public synchronized Iterator<E> iterator() {
        return new Itr();
    }      

Vector類中的Itr私有類實作Iterator接口

// 繼承Iterator
    private class Itr implements Iterator<E> {
        // 光标指向元素的前面,初始光标指向向量第一個元素的前面.
        // 舉例 : ^ 1 2 3 4 5 (每次向後移動,光标的值都會加一)
        // 向後移:1 ^ 2 3 4 5
        // ...
        // 移到最後:1 2 3 4 5 ^
        // 當移動到最後時,此時光标的值為5,與向量的實際大小相等
        int cursor;       // index of next element to return
        // 每當光标移動後,lastRet的值都等于光标移動前的值.初始為-1
        int lastRet = -1; // index of last element returned; -1 if no such
        // 期望修改的次數初始與修改的次數相等
        int expectedModCount = modCount;

        // 判斷光标後面是否還有值
        public boolean hasNext() {
            // Racy but within spec, since modifications are checked
            // within or after synchronization in next/previous
            // 若光标已經移到了最後,光标大小為5,與元素的實際大小相等,傳回false,證明元素之後沒值的标準
            return cursor != elementCount;
        }

        // 取出光标後的值,并将光标後移一位
        public E next() {
            synchronized (Vector.this) {
                // 先檢測向量是否被修改過
                checkForComodification();
                int i = cursor;
                // 判斷光标之後是否有值
                if (i >= elementCount)
                    throw new NoSuchElementException();
                // 光标後移一位
                cursor = i + 1;
                // 取出光标移動之前所在的值
                // ^ 1 2 3 4 5
                // 光标在第一個元素之前的話,光标的值為0,那麼取出的值也就是elementData[0],
                // 然後光标的值加1(也就是所謂的後移一位. 1 ^ 2 3 4 5)
                // 在此調用next()方法時,光标已經加1,那麼取出的值也就是elementData[1],
                // 光标繼續後移一位(也就是指向第二個元素的後面, 1 2 ^ 3 4 5)
                return elementData(lastRet = i);
            }
        }

        // Iterator類中自帶的remove()方法
        public void remove() {
            // 先判斷光标是否移動過,光标移動後,将光标移動前的值指派給lastRet
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                // 借助Vector的remove方法,此時modCount的值會加1
                Vector.this.remove(lastRet); // 将移除光标前的元素
                // Iterator不允許其他類的增删操作,隻允許自己,                
                // 删除元素之後把修改過的次數重新指派預期修改的次數
                expectedModCount = modCount;
                // 這樣也就好了解了.自己類的增删操作,是可以預期的,
                // 而疊代類之外的操作光标的位置啥的都亂了,難以維護,可能也是為了避免繁瑣的邏輯,直接不允許其他類在疊代的時候進行操作
            }
            // 删除元素之後,重新維護光标的位置,此時光标向前移1位
            // 舉例 : 1 2 3 ^ 4 5 (此時執行remove()方法)
            // 删後 : 1 2   ^ 4 5 (此時4個元素,光标的值位3,但光标很明顯在第二值的後面嘛
            // 是以,光标向前移一位
            cursor = lastRet;
            // 最後一個元素被删除,傳回的最後一個元素沒值,是以重置lastRet的值為-1
            lastRet = -1;
            // 也正是因為被重置為-1,是以不允許連續進行remove方法,需要移動之後才可以繼續執行remove方法.
        }

        @Override
        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            synchronized (Vector.this) {
                final int size = elementCount;
                int i = cursor;
                if (i >= size) {
                    return;
                }
        @SuppressWarnings("unchecked")
                final E[] elementData = (E[]) Vector.this.elementData;
                if (i >= elementData.length) {
                    throw new ConcurrentModificationException();
                }
                while (i != size && modCount == expectedModCount) {
                    action.accept(elementData[i++]);
                }
                // update once at end of iteration to reduce heap write traffic
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
        }

        final void checkForComodification() {
            // 判斷是否進行過疊代的方法之外的增删操作
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * An optimized version of AbstractList.ListItr
     */
     // 該類與Iterator相比,增加了向前周遊的方法,而且增加了修改與增加元素,
     // 且該類繼承了Iterator類,是以上面的方法該類也是同樣适用的
    final 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;
        }

        // 與next()方法正好相反,向前周遊,光标并且向左移一位
        public E previous() {
            synchronized (Vector.this) {
                checkForComodification();
                int i = cursor - 1;
                if (i < 0)
                    throw new NoSuchElementException();
                cursor = i;
                return elementData(lastRet = i);
            }
        }

        // 修改光标之前的元素
        public void set(E e) {
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.set(lastRet, e);
                // 因為隻是修改元素的值,并未改變向量中元素的位置,光标并未受到影響
            }
        }

        // 添加元素,将元素添加到光标之後的位置
        public void add(E e) {
            int i = cursor;
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.add(i, e);
                expectedModCount = modCount;
            }
            // 光标的位置向後移一位 
            cursor = i + 1;
            lastRet = -1;
        }
    }

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

    @Override
    @SuppressWarnings("unchecked")
    public synchronized boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final int size = elementCount;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        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();
        }

        // shift surviving elements left over the spaces left by removed elements
        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;  // Let gc do its work
            }
            elementCount = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = elementCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    @SuppressWarnings("unchecked")
    @Override
    public synchronized void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, elementCount, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

                      
    @Override
    public Spliterator<E> spliterator() {
        return new VectorSpliterator<>(this, null, 0, -1, 0);
    }

    /** Similar to ArrayList Spliterator */
    static final class VectorSpliterator<E> implements Spliterator<E> {
        private final Vector<E> list;
        private Object[] array;
        private int index; // current index, modified on advance/split
        private int fence; // -1 until used; then one past last index
        private int expectedModCount; // initialized when fence set

        /** Create new spliterator covering the given  range */
        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
                          int expectedModCount) {
            this.list = list;
            this.array = array;
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        private int getFence() { // initialize on first use
            int hi;
            if ((hi = fence) < 0) {
                synchronized(list) {
                    array = list.elementData;
                    expectedModCount = list.modCount;
                    hi = fence = list.elementCount;
                }
            }
            return hi;
        }

        public Spliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null :
                new VectorSpliterator<E>(list, array, lo, index = mid,
                                         expectedModCount);
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super E> action) {
            int i;
            if (action == null)
                throw new NullPointerException();
            if (getFence() > (i = index)) {
                index = i + 1;
                action.accept((E)array[i]);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi; // hoist accesses and checks from loop
            Vector<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null) {
                if ((hi = fence) < 0) {
                    synchronized(lst) {
                        expectedModCount = lst.modCount;
                        a = array = lst.elementData;
                        hi = fence = lst.elementCount;
                    }
                }
                else
                    a = array;
                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
                    while (i < hi)
                        action.accept((E) a[i++]);
                    if (lst.modCount == expectedModCount)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        public long estimateSize() {
            return (long) (getFence() - index);
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
}      
  1. 作者:歐陽思海