Vector源碼解析


Vector簡介

1、Vector是矢量隊列。它是jdk1.0版本添加的類 繼承 AbstractList、實現 List, RandomAccess, Cloneable, java.io.Serializable 這些接口

2、繼承 AbstractList,實現List.所有它是一個對隊列。支持隊列相關的操作

3、Vector 實現 RandomAccess 所有提供隨機訪問功能,RandmoAccess是java中用來被List實現,為List提供快速訪問功能的。在Vector中,我們即可以通過元素的序號快速獲取元        素對象;這就是快速隨機訪問。

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

5、Vector 是線程安全的,但也導致了性能要低於ArrayList

 

Vector的繼承關系圖

 

 

Vector源碼解析 

package java.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
public class Vector<E>
        extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    //這就是存儲數據的數組,注意啦這是一個動態的數組
    protected Object[] elementData;

    //當前元素的個數
    protected int elementCount;

    //容量增長系數,擴容時使用
    protected int capacityIncrement;

    // Vector的序列版本號
    private static final long serialVersionUID = -2767605614048989439L;

    //指定數組的初始化大小,和增長系數。容量不能小於0
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                    initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

   //指定容量,增長系數未 0
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    //采用默認 容量 10 增長系數為 0
    public Vector() {
        this(10);
    }

    //使用另一個集合構造改集合
    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray可能(錯誤地)不返回Object []
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }


    //這時將Veector中的所有數據都拷貝到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) {
            //使用Arrays.copyOf方法將數據中的元素copy到新數組中
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }


    //如有必要,增加當前數組的容量,以確保至少可以保存minCapacity容量參數指定的元素個數
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }


    /**
     * 和上面方法的功能一樣,這么做的原因是這是一個內部使用的方法,使用就沒有必要去同步,這樣的好處就是可用
     * 降低同步所帶來的開銷
     */
    private void ensureCapacityHelper(int minCapacity) {
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    //當前數組的最大容量,其實擴容可用擴容到 Integer.MAX_VALUE往下面看就知道了
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    //Vectory的擴容方法,嗯嗯看看它的擴容機制吧
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        //新的數組長度 = 舊數組長度 + 增長系數大於0加增長系數 否則 + 舊數組長度
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                capacityIncrement : oldCapacity);
        //如果計算后還不夠就 = 最小擴容數
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //如果大於最大擴容數
        if (newCapacity - MAX_ARRAY_SIZE > 0)
        /**
         * hugeCapacity 返回 嗯嗯從這我們可用看錯最大看擴容量位Integer.MAX_VALUE
         * (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE : MAX_ARRAY_SIZE;
         *
         */
            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;
    }

    //設置當前數組的元素個數,如果小於當前元素的個數
    //那么就將多出來的元素置空,如果大於數組擴容
    public synchronized void setSize(int newSize) {
        modCount++;
        if (newSize > elementCount) {
            ensureCapacityHelper(newSize);
        } else {
            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;
    }


    //返回“Vector中全部元素對應的Enumeration(枚舉)
    public Enumeration<E> elements() {
        //通過匿名類實現 Enumeration 接口
        return new Enumeration<E>() {
            int count = 0;

            public boolean hasMoreElements() {
                return count < elementCount;
            }

            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

    //是否包含指定元素
    public boolean contains(Object o) {
        //從頂一位開始查找 通過 >= 0 判斷是否包含
        return indexOf(o, 0) >= 0;
    }

    //返回指定元素在數組中的位置
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    //指定元素 開始位置 返回改元素在數組中的下標
    public synchronized int indexOf(Object o, int index) {
        //判斷以下是否位空,為空 用 == 不位空用 equals
        if (o == null) {
            //循環查找,找到返回
            for (int i = index ; i < elementCount ; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index ; i < elementCount ; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        //如果每找到返回狀態碼 -1
        return -1;
    }

   //重后往前找,元素在數組中的位置。重最后一個元素開始找起
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount-1);
    }

    //指定查找元素和查找起始位置。從后往前找
    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;
        }
        //找不到一樣返回狀態碼 -1
        return -1;
    }

    //返回指定下標處的元素
    public synchronized E elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }

        return elementData(index);
    }

    //返回第一個元素
    public synchronized E firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    //返回最后一個元素
    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }

    //修改指定位置的元素
    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) {
            //移動數組位置:新數組位置 = 原數組移除元素的后一位都通過copy向前移動一位
            System.arraycopy(elementData, index + 1, elementData, index, j);
        }
        elementCount--;
        //copy會多出來一位,設置位null 讓gc做它的工作
        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);
        //通過arraycopy方法在插入位置向后移動以為,方便元素插入
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        elementData[index] = obj;
        elementCount++;
    }

    //添加元
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

    //移除元素
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        //通過 indexOf獲取在數組中的位置
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    //刪除當前數組中的所有元素
    public synchronized void removeAllElements() {
        modCount++;
        //讓gc做它的工作
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

    //克隆函數
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
            Vector<E> v = (Vector<E>) super.clone();
            //將當前Vector的全部元素拷貝到v中
            v.elementData = Arrays.copyOf(elementData, elementCount);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    //返回存有當前集合所有元素引用的數組
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

    // 返回Vector的模板數組。所謂模板數組,即可以將T設為任意的數據類型
    @SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
        //如果a的大小小於當前元素的個數 那么就建立新的數組返回
        //如果a的大小大於或等於當前元素的大小就將元素copy到a數組中去
       if (a.length < elementCount)
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());

        System.arraycopy(elementData, 0, a, 0, elementCount);

        if (a.length > elementCount)
            a[elementCount] = null;

        return a;
    }

    //返回指定位置的元素 這個是內部使用 不加鎖,但加鎖的那個方法
    //也是調用此方法。看下面的get方法就指定了
    @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;
    }

    //添加元素
    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();
    }



    //如果此Vector包含指定Collection中的所有元素,則返回true
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    //將指定集合的所有數據都添加進當前集合
    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;
    }


    //當前Vectory中包含指定集合中的元素通通移除掉
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }


    //刪除“非集合c中的元素”
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

    // 從index位置開始,將集合c中所有元素添加到Vector中
    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;
    }

    //Vector的equals實現,就是調用父類AbstractList的equals方法
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }

    //hashCode碼
    public synchronized int hashCode() {
        return super.hashCode();
    }

    //將當前對象轉換位字符串
    public synchronized String toString() {
        return super.toString();
    }

    //獲取Vector中fromIndex(包括)到toIndex(不包括)的子集
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
                this);
    }

    //移除Vectory中 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();
    }

    ///這是返回ListIterator迭代器的方法,指定迭代的開始位置
    public synchronized ListIterator<E> listIterator(int index) {
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    //開始位置位 0 定死
    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

   //這是返回iterator迭代器
    public synchronized Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * AbstractList.Itr的優化版本 的迭代器實現類
     */
    private class Itr implements Iterator<E> {
        int cursor;       //要返回的下一個元素的索引
        int lastRet = -1; // 返回最后一個元素的索引; -1如果沒有,
        int expectedModCount = modCount;

        //是否還有下一位
        public boolean hasNext() {
            return cursor != elementCount;
        }

        //返回下一位
        public E next() {
            synchronized (Vector.this) {
                checkForComodification();
                int i = cursor;
                if (i >= elementCount)
                    throw new NoSuchElementException();
                cursor = i + 1;
                return elementData(lastRet = i);
            }
        }


        //移除當前所在光標的元素
        public void remove() {
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.remove(lastRet);
                expectedModCount = modCount;
            }
            cursor = lastRet;
            lastRet = -1;
        }

        //這是jdk 1.8新增加的方法,重當前迭代位置開始 每個元素都執行 action的指定操作
        @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++]);
                }
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * AbstractList.ListItr的優化版本 ListIterator 實現
     */
    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;
        }

        //返回上以為,並移動光標
        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;
        }
    }


    //遍歷執行 action 方法
    @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();
        }

        // 移位幸存元素留在被移除元素留下的空間
        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")
    //循環遍歷 將執行operator返回的元素替換當前元素
    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
    //這是給當前的數據進行排序的方法 Comparator 定義了排序的規則
    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++;
    }

   //當前數據中創建Spliterator
    @Override
    public Spliterator<E> spliterator() {
        return new VectorSpliterator<>(this, null, 0, -1, 0);
    }

    //與ArrayList Spliterator類似
    static final class VectorSpliterator<E> implements Spliterator<E> {
        private final Vector<E> list;
        private Object[] array;
        private int index; // 當前指數,在提前/拆分時修改
        private int fence; // -1直到使用;然后是最后一個索引
        private int expectedModCount; //柵欄設置時初始化

        /** 創建覆蓋給定范圍的新分裂器*/
        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() { // 首次使用時初始化 返回數組的元素個數
            int hi;
            if ((hi = fence) < 0) {
                synchronized(list) {
                    array = list.elementData;
                    expectedModCount = list.modCount;
                    //hi就等於 = list.elementCount 元素個數
                    hi = fence = list.elementCount;
                }
            }
            return hi;
        }

        //重當前對象再分割一個 Spliterator
        public Spliterator<E> trySplit() {
            // hi = list.elementCount                                    
            int hi = getFence(),
                    lo = index,
                    //(lo + hi) / 2
                    mid = (lo + hi) >>> 1;
            //看看是否還能拆分出一個 Spliterator 如果拆分不了返回null
            return (lo >= mid) ? null :
                    new VectorSpliterator<E>(list, array, lo, index = mid,
                            expectedModCount);
        }

        @SuppressWarnings("unchecked")
        //將index + 1位執行 action定義的方法 這是jdk 1.8函數編程所提供出來的
        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")
        //使用函數式編程 循環數組執行 actioin
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi; // 提升從循環訪問和檢查
            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、Vector是使用數組保存數據,和ArrayList套路一樣

2、如果每有指定構造Vector那么它的默認容量位 10 增長系數位 0

3、擴容機制:如果增長系數不位 0 那么就是當前容量  + 增長系數,否則就的當前容量加一倍 更詳細的化還是看看上面的ensureCapacity()函數,最的擴容量是Integer.MAX_VALUE

4、Vector的克隆函數,即是將全部元素克隆到一個數組中。

遍歷方式

1、Iterator迭代器

 Iterator iterator = vector.iterator();
        while (iterator.hasNext()){
            iterator.next();
}

 

2、java 8 新特性來遍歷元素

vector.forEach(a -> {});

 

3、for循環 使用了隨機范圍的機制

for (int i = 0; i < vector.size(); i++) {
           vector.get(i);
}

 

4、Enumeration 遍歷

   for (Enumeration enu = vector.elements(); enu.hasMoreElements(); ){
            enu.nextElement();
        }

 

5、foreach循環

 for (Object o: vector) {
      System.out.println(o);  
}

 

各種遍歷的性能比較

   public static void main(String[] args) {
        Vector vec = new Vector();
        for(int i = 0; i < 10000000; i ++)
            vec.add(i);
        iteratorThroughRandomAccess(vec);
        iteratorThroughIterator(vec);
        iteratorThroughJ8(vec);
        iteratorEnumeration(vec);
        iteratorForEach(vec);
    }

    public static void iteratorThroughRandomAccess(Vector vector){
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        for (int i = 0; i < vector.size(); i++) {
                vector.get(i);
        }
        endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println("for循環" + interval + "毫秒");
    }
    
    public static void iteratorThroughIterator(Vector vector){
       long startTime;
       long endTime;
       startTime = System.currentTimeMillis();
        Iterator iterator = vector.iterator();
        while (iterator.hasNext()){
            iterator.next();
        }
        endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println("迭代器遍歷" + interval + "毫秒");
    }

    public static void iteratorThroughJ8(Vector vector){
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        vector.forEach(a -> {});
        endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println("jdk1.8新特性遍歷" + interval + "毫秒");
    }
    
    public static void iteratorEnumeration(Vector vector){
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        for (Enumeration enu = vector.elements(); enu.hasMoreElements(); ){
            enu.nextElement();
        }
        endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println("java 枚舉遍歷歷" + interval + "毫秒");
    }
    
    public  static void iteratorForEach(Vector vector){
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        for (Object o: vector) ;
        endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println("foreach循環" + interval + "毫秒");

    }

執行結果:

使用隨機訪問遍歷479毫秒
迭代器 iterator遍歷242毫秒
jdk1.8新特性遍歷58毫秒
java 枚舉遍歷歷149毫秒
foreach循環143毫秒

 

參考博客:

https://www.cnblogs.com/skywang12345/p/3308833.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM