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

posted @ 2019-05-21 09:06  小cai一碟  阅读(2775)  评论(2编辑  收藏  举报