java源码之Vector(jdk8)

前言

Vector是一个开一改变大小的集合,其底层实现为数组,在创建时如果没有指定大小,默认大小为10,可以指定扩容容量,如果不指定,每次扩容后大小为为原来的2倍。Vector是集合安全的,他的安全方式是方法由synchronized修饰。

集成关系

Vector实现的接口有Serializable , Cloneable , Iterable , Collection , List , RandomAccess
Vector的子类有Stack

源码

public class Vector<E>
        extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    /**
     * 存储集合数据的数组
     */
    protected Object[] elementData;

    /**
     * 集合数据场地
     */
    protected int elementCount;

    /**
     * 每次自动扩容大小,可指定,如果未指定扩充为原来的两倍
     */
    protected int capacityIncrement;

    /**
     * use serialVersionUID from JDK 1.0.2 for interoperability
     */
    private static final long serialVersionUID = -2767605614048989439L;

    /**
     * 指定容量和扩容容量大小的构造函数
     *
     * @param initialCapacity   初始容量
     * @param capacityIncrement 每次扩容的容量大小
     * @throws IllegalArgumentException 如果指定容量小于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;
    }

    /**
     * 指定初始容量大小的构造函数
     *
     * @param initialCapacity 初始容量
     * @throws IllegalArgumentException 如果指定容量小于0
     */
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    /**
     * 不指定大小的 默认大小为10
     */
    public Vector() {
        this(10);
    }

    /**
     * 指定集合所有元素的集合
     *
     * @param c 指定集合
     * @throws NullPointerException 如果指定集合为null抛出NPE
     * @since 1.2
     */
    public Vector(Collection<? extends E> c) {
        /**
         * 获取数据
         */
        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);
    }

    /**
     * 将集合中的数据复制到指定数组中
     *
     * @param anArray 复制数据的指定数组
     * @throws NullPointerException      如果指定数组为null抛出此异常
     * @throws IndexOutOfBoundsException 如果指定的数组无法完全容纳集合中的数据抛出此异常
     * @throws ArrayStoreException       如果数组类型和集合类型不一致
     * @see #toArray(Object[])
     */
    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);
        }
    }

    /**
     * 按照期望容量进行集合扩容
     * <p>
     * 尝试以期望的最小容量作为基础进行进行集合扩容
     *
     * @param minCapacity 期望的最小容量
     */
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

    /**
     * 数组扩容检测
     * 属于ensureCapacity的非同步方法,在不产生成本的条件下进行集合扩容
     *
     * @see #ensureCapacity(int)
     */
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        // 使用减法避免int溢出问题
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 要分配的数组的最大大小。
     * 一些vm在数组中保留一些头字。
     * 尝试分配更大的阵列可能会导致
     * OutOfMemoryError:请求的数组大小超过VM限制
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 集合扩容
     *
     * @param minCapacity 扩容要求最小长度
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 计算新的扩容长度 如果指定的扩容大小大于0 即扩大扩容大小 否则扩容增加原始大小 所以Vector默认扩容为原来的两倍
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                capacityIncrement : oldCapacity);
        // 比较新的扩容大小和扩容需求最小长度
        // 使用减法避免int溢出问题
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        // 扩容后大小超过MAX_ARRAY_SIZE
        // 使用减法避免int溢出问题
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            // 获取集合较大时的数组大小
            newCapacity = hugeCapacity(minCapacity);
        // 数据拷贝
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    /**
     * 数组长度较大时进行判断
     *
     * @param minCapacity 数组扩容最小要求长度
     * @return
     */
    private static int hugeCapacity(int minCapacity) {
        // 扩容长度小于0 int溢出
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        // 数组大于集合默认最大值 使用int最大值 否则使用集合默认最大值
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }

    /**
     * 设置集合大小
     *
     * @param newSize 新集合大小
     * @throws ArrayIndexOutOfBoundsException 设置大小为负数抛出此异常
     */
    public synchronized void setSize(int newSize) {
        modCount++;
        // 比较设置到校和集合原来大小
        if (newSize > elementCount) {
            // 如果集合设置大小大于原始大小进行扩容及数据拷贝到扩容后的数组中
            ensureCapacityHelper(newSize);
        } else {
            // 否则将集合超出部分的数据设置为null
            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;
    }

    /**
     * 获取集合中数据枚举
     *
     * @return 获取集合中的枚举
     * @see Iterator
     */
    public Enumeration<E> elements() {
        return new Enumeration<E>() {
            // 当前访问位置
            int count = 0;

            /**
             * 是否由下一个元素
             * @return
             */
            public boolean hasMoreElements() {
                return count < elementCount;
            }

            /**
             * 获取元素
             * @return
             */
            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

    /**
     * 判断集合是否包含某个远古三
     *
     * @param o 是否包含的元素
     * @return {@code true} if this vector contains the specified element
     */
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    /**
     * 获取指定元素第一次出现的位置
     *
     * @param o 指定元素
     * @return 指定元素的位置,如果指定元素不存在则返回-1
     */
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    /**
     * 获取从开始位置开始第一次出现指定元素的位置
     *
     * @param o     指定元素
     * @param index 开始位置
     * @return 指定元素的位置,如果指定元素不存在则返回-1
     * @throws IndexOutOfBoundsException 如果指定位置为负数
     * @see Object#equals(Object)
     */
    public synchronized int indexOf(Object o, int index) {
        if (o == null) {
            // 如果元素为null使用==进行比较
            for (int i = index; i < elementCount; i++)
                if (elementData[i] == null)
                    return i;
        } else {
            // 否则使用equasl进行比较
            for (int i = index; i < elementCount; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * 获取制定元素最后一次出现的位置
     *
     * @param o 指定元素
     * @return 指定最后元素的位置,如果指定元素不存在则返回-1
     */
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount - 1);
    }

    /**
     * 获取从指定位置之前指定元素最后一次出现的位置
     *
     * @param o     指定元素
     * @param index 指定位置
     * @return 指定最后元素的位置,如果指定元素不存在则返回-
     * @throws IndexOutOfBoundsException 如果指定位置大于等于集合数量
     */
    public synchronized int lastIndexOf(Object o, int index) {
        // 判断指定位置
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= " + elementCount);

        // 判断元素位置
        if (o == null) {
            // 如果元素为null使用==进行比较
            for (int i = index; i >= 0; i--)
                if (elementData[i] == null)
                    return i;
        } else {
            // 否则使用equasl进行比较
            for (int i = index; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * 获取指定位置的元素
     * <p>
     * 这个方法在功能上和{@link #get(int)}相同
     *
     * @param index 指定位置
     * @return 指定位子的元素
     * @throws ArrayIndexOutOfBoundsException 如果指定位置超出集合抛出此异常
     */
    public synchronized E elementAt(int index) {
        // 判断位置合法
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }
        // 获取指定位置数据
        return elementData(index);
    }

    /**
     * 获取集合中第一个元素即get(0)或者elementAt(0)
     *
     * @return 集合的第一个元素
     * @throws NoSuchElementException 如果集合不包含任何元素
     */
    public synchronized E firstElement() {
        // 判断集合有没有元素
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        //返回第一个元素
        return elementData(0);
    }

    /**
     * 获取集合最后一个元素
     *
     * @return 集合的最有一个远古三
     * @throws NoSuchElementException 如果集合不包含任何元素抛出此异常
     */
    public synchronized E lastElement() {
        // 判断集合有没有元素
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        //返回最后一个元素
        return elementData(elementCount - 1);
    }

    /**
     * 将指定位置的元素替换掉,原来的元素抛弃
     * <p>
     * <p>
     * 者个方法在功能上和{@link #set(int, E)}相同
     *
     * @param obj   替换数据
     * @param index 替换位置
     * @throws ArrayIndexOutOfBoundsException 替换位置小于0或者替换位置超出数组
     */
    public synchronized void setElementAt(E obj, int index) {
        // 判断为止
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    elementCount);
        }
        // 替换元素
        elementData[index] = obj;
    }

    /**
     * 删除指定位置的元素,删除之后所有元素左移,并且集合长度减一
     * <p>
     * 其功能类似 {@link #remove(int)}
     *
     * @param index 删除元素的指定位置
     * @throws ArrayIndexOutOfBoundsException 如果删除位置小于0或者超出数组
     */
    public synchronized void removeElementAt(int index) {
        modCount++;
        // 判断删除位置
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    elementCount);
        } else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        // 判断移动元素数量
        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 */
    }

    /**
     * 在指定位置插入元素,其后元素全部后移
     * <p>
     * 功能上与{@link #add(int, E)}
     *
     * @param obj   插入的数据
     * @param index 指定位置
     * @throws ArrayIndexOutOfBoundsException 如果删除位置小于0或者超出数组
     */
    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        // 判断添加位置
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index
                    + " > " + elementCount);
        }
        // 容量检查
        ensureCapacityHelper(elementCount + 1);
        //  数据拷贝
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        // 赋值
        elementData[index] = obj;
        elementCount++;
    }

    /**
     * 将指定元素插入集合尾部
     * 此功能与{@link #add(E)}相同
     *
     * @param obj 插入集合的元素
     */
    public synchronized void addElement(E obj) {
        modCount++;
        // 容量检查
        ensureCapacityHelper(elementCount + 1);
        // 赋值
        elementData[elementCount++] = obj;
    }

    /**
     * 删除集合中的指定元素
     * 此功能与{@link #remove(Object)}相似
     *
     * @param obj 删除的元素
     * @return 是否删除成功
     */
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        // 元素所在位置
        int i = indexOf(obj);
        if (i >= 0) {
            // 按位置删除元素
            removeElementAt(i);
            return true;
        }
        return false;
    }

    /**
     * 删除集合中所有元素
     * 此功能与{@link #clear}相同
     */
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

    /**
     * 获取集合的拷贝
     * 如果集合中的元素并没有新建对象,所以改变集合中的元素会引起另一个集合元素改变
     *
     * @return a clone of this vector
     */
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
            Vector<E> v = (Vector<E>) super.clone();
            // 拷贝数据
            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);
        }
    }

    /**
     * 获取集合中所有元素组成的数组
     *
     * @since 1.2
     */
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

    /**
     * 按照指定类型数组获取集合中所有元素
     *
     * @param a 指定类型数组
     * @throws ArrayStoreException  指定数组类型不是集合元素的类型或者父类型
     * @throws NullPointerException 给定数组为空
     * @since 1.2
     */
    @SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
        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;

        return a;
    }

    // Positional Access Operations

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

    /**
     * 获取指定位置的元素
     *
     * @param index 指定位置
     * @return 指定位置的元素
     * @throws ArrayIndexOutOfBoundsException 指定位置不合法小于0或者大于集合长度
     * @since 1.2
     */
    public synchronized E get(int index) {
        // 验证位置合法性
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        // 获取数据
        return elementData(index);
    }

    /**
     * 替换指定位置元素
     *
     * @param index   指定位置
     * @param element 替换元素
     * @return 被替换的数据
     * @throws ArrayIndexOutOfBoundsException 指定位置不合法小于0或者大于集合长度
     * @since 1.2
     */
    public synchronized E set(int index, E element) {
        // 验证替换位置合法性
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        // 获取原始数据
        E oldValue = elementData(index);
        // 替换数据
        elementData[index] = element;
        return oldValue;
    }

    /**
     * 在集合末尾添加元素
     *
     * @param e 添加的元素
     * @return {@code true} (as specified by {@link Collection#add})
     * @since 1.2
     */
    public synchronized boolean add(E e) {
        modCount++;
        // 确保容量
        ensureCapacityHelper(elementCount + 1);
        // 数据赋值 集合长度递增
        elementData[elementCount++] = e;
        return true;
    }

    /**
     * 删除集合中第一次出现的指定元素
     *
     * @param o 指定元素
     * @return 如果包含此元素(删除成功)返回true
     * @since 1.2
     */
    public boolean remove(Object o) {
        return removeElement(o);
    }

    /**
     * 在指定位置添加一个元素
     *
     * @param index   插入元素的指定位置
     * @param element 插入元素
     * @throws ArrayIndexOutOfBoundsException 指定位置不合法小于0或者大于集合长度
     * @since 1.2
     */
    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    /**
     * 删除指定位置的元素,后面元素需要往前移动
     *
     * @param index 删除的指定位置
     * @return 被删除的数据
     * @throws ArrayIndexOutOfBoundsException 指定位置不合法小于0或者大于集合长度
     * @since 1.2
     */
    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)
            // 移动元素数量大于0进行数组数据移动
            System.arraycopy(elementData, index + 1, elementData, index,
                    numMoved);
        // 数组末尾设为null
        elementData[--elementCount] = null; // Let gc do its work

        return oldValue;
    }

    /**
     * 删除集合中全部元素
     *
     * @since 1.2
     */
    public void clear() {
        removeAllElements();
    }

    // Bulk Operations

    /**
     * 获取是否包含指定集合全部元素
     *
     * @param c 指定集合
     * @return 是否包含指定集合全部元素
     * @throws NullPointerException 如果指定集合为null
     */
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    /**
     * 将指定集合中的元素全部加入到集合中
     *
     * @param c 指定集合
     * @return 是否有新的元素加入集合
     * @throws NullPointerException 如果指定集合为null抛出此异常
     * @since 1.2
     */
    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;
    }

    /**
     * 删除指定集合中全部元素
     *
     * @param c 指定集合
     * @return 是否删除集合中的元素
     * @throws ClassCastException   如果删除集合中的元素和集合的类型不同
     * @throws NullPointerException 如果指定集合中包含null,但是指定集合不支持null值
     * @since 1.2
     */
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    /**
     * 删除不在指定集合中的元素(交集)
     *
     * @param c 指定集合
     * @return true if this Vector changed as a result of the call
     * @throws ClassCastException   指定集合中的元素类型和集合的类型不兼容
     * @throws NullPointerException 如果指定集合中包含null,但是指定集合不支持null值
     * @since 1.2
     */
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

    /**
     * 在指定位置插入指定集合
     *
     * @param index 指定位置
     * @param c     指定集合
     * @return {@code true} if this Vector changed as a result of the call
     * @throws ArrayIndexOutOfBoundsException 如果指定位置不合法,指定位置小于0或者指定位置大于集合长度
     * @since 1.2
     */
    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;
    }

    /**
     * 判断指定集合是否和当前集合想等
     *
     * @param o 指定结合
     * @return true if the specified Object is equal to this Vector
     */
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }

    /**
     * 返回集合的hash值.
     */
    public synchronized int hashCode() {
        return super.hashCode();
    }

    /**
     * 重写toString方法
     */
    public synchronized String toString() {
        return super.toString();
    }

    /**
     * 返回从开始位置(包括)到结束位置(不包括)的元素集合
     *
     *
     * @param fromIndex 开始位置
     * @param toIndex   结束为止
     * @return a view of the specified range within this List
     * @throws IndexOutOfBoundsException 开始位置小于0或者结束位置超过数组长度
     * @throws IllegalArgumentException  如果开始位置大约结束为止
     */
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        // 使用Collections.synchronizedList实现
        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
                this);
    }

    /**
     * 移除从开始位置(包括)到结束位置(不包括)的全部元素
     */
    protected synchronized void removeRange(int fromIndex, int toIndex) {
        modCount++;
        // 计算移动数量
        int numMoved = elementCount - toIndex;
        // 数组前移
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                numMoved);

        // 计算数组长度
        int newElementCount = elementCount - (toIndex - fromIndex);
        // Let gc do its work
        // 多元素置为null
        while (elementCount != newElementCount)
            elementData[--elementCount] = null;
    }

    /**
     *
     * 读取刘中的数据 反序列化
     * @param in the stream
     * @throws java.io.IOException    if an I/O error occurs
     * @throws ClassNotFoundException if the stream contains data
     *                                of a non-existing class
     */
    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();
    }

    /**
     * 从指定位置获取列表迭代器
     *
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public synchronized ListIterator<E> listIterator(int index) {
        // 验证指定位置
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: " + index);
        return new ListItr(index);
    }

    /**
     * 获取从开始位置的列表迭代器
     *
     * @see #listIterator(int)
     */
    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 获取集合的迭代器
     *
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public synchronized Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * 迭代器实现
     */
    private class Itr implements Iterator<E> {
        // 下一个元素的下标
        int cursor;       // index of next element to return
        // 上一个返回元素的小标
        int lastRet = -1; // index of last element returned; -1 if no such
        // 期望修改值 用来实现fail-fast策略
        int expectedModCount = modCount;

        // 是否有下一个元素
        public boolean hasNext() {
            // Racy but within spec, since modifications are checked
            // within or after synchronization in next/previous
            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() {
            // 如果上次未返回或者已经被删除是为-1
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                // 检查修改
                checkForComodification();
                // 删除元素
                Vector.this.remove(lastRet);
                // 修改期望值
                expectedModCount = modCount;
            }
            // 修改下一个访问元素下标
            cursor = lastRet;
            // 修改上一个返回元素下标
            lastRet = -1;
        }

        // 循环调用指定某个操作
        @Override
        public void forEachRemaining(Consumer<? super E> action) {
            // 操作不能是null
            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();
        }
    }

    /**
     * 列表迭代器
     */
    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;
        }
    }

    // 循环调用指定某个操作
    @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;
        // 使用BitSet对象记录要移除元素的下标
        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)) {
                // 满足条件 删除数量+1
                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开始 返回位置为false的第一个索引
                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++;
    }

    /**
     * 获取集合分割迭代器
     *
     * @return a {@code Spliterator} over the elements in this list
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new VectorSpliterator<>(this, null, 0, -1, 0);
    }

    /**
     * 分割迭代器
     */
    static final class VectorSpliterator<E> implements Spliterator<E> {
        // 原始集合
        private final Vector<E> list;
        // 数组 集合在第一次调用的时候 为null 在调用VectorSpliterator中的方法后会把变为集合的数组
        private Object[] array;
        // 开始位置 在trySplit和tryAdvance都会修改
        private int index; // current index, modified on advance/split
        // 结束位置 集合在第一次调用的时候 为-1 在调用VectorSpliterator中的方法后会把变为集合的长度
        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;
        }

       // 获取fence值 即集合结束值
        private int getFence() { // initialize on first use
            int hi;
            // 如果集合截数据小于0
            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();

            // 集合不为null
            if ((lst = list) != null) {
                if ((hi = fence) < 0) {
                    // 集合结束位置小于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);
        }

        //返回当前对象有哪些特征值
        // ORDERED 元素之间是有顺序的
        // SIZED 表示长度为有限个
        // SUBSIZED 迭代器所分割得到的子迭代器也是有序的
        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
}

成员变量

elementData

vector集合存储数据的地方

protected Object[] elementData;
elementCount

集合长度(数组有效长度)

protected int elementCount;
capacityIncrement

每次自动扩容大小,可指定,如果未指定扩充为原来的两倍

protected int capacityIncrement;
MAX_ARRAY_SIZE

集合最大长度

 /**
     * 要分配的数组的最大大小。
     * 一些vm在数组中保留一些头字。
     * 尝试分配更大的阵列可能会导致
     * OutOfMemoryError:请求的数组大小超过VM限制
     */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

构造函数

Vector()

无参构造,默认初始容量为10,每次扩容为原来两倍

 public Vector() {
        this(10);
    }
Vector(int initialCapacity)

使用初始容量,每次扩容为原来两倍

 /**
     * 指定初始容量大小的构造函数
     *
     * @param initialCapacity 初始容量
     * @throws IllegalArgumentException 如果指定容量小于0
     */
  public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }
Vector(int initialCapacity, int capacityIncrement)

使用指定初始容量和扩充容量,如果扩充容量小于等于0扩容至两倍

/**
     * 指定容量和扩容容量大小的构造函数
     *
     * @param initialCapacity   初始容量
     * @param capacityIncrement 每次扩容的容量大小
     * @throws IllegalArgumentException 如果指定容量小于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;
    }
Vector(Collection<? extends E> c)

使用指定集合进行创建集合,集合长度为指定集合数组长度

 /**
     * 指定集合所有元素的集合
     *
     * @param c 指定集合
     * @throws NullPointerException 如果指定集合为null抛出NPE
     * @since 1.2
     */
    public Vector(Collection<? extends E> c) {
        /**
         * 获取数据
         */
        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);
    }

扩容机制

ensureCapacityHelper进行数组扩容检测,检测最小需求数组大小能否被当前的数组满足,如果不满足调用grow进行扩容;
grow进行集合扩容操作,首先获取原始数组大小,然后按照指定扩容大小大于0直接扩大指定扩容大小,否则扩大一倍。如果扩大后的长度仍不能满足数组最小需求,那么扩容后的大小为数组最小需求,如果扩容后的大小大于默认数组最大值,调用hugeCapacity获取集合大小,然后拷贝数据;
hugeCapacity在判断集合较大时,如果最小需求长度为负值(数据溢出)直接抛出OOM,如果最小需求长度大于默认数组最大值,那么数组长度为Integer最大值,否则为默认数组最大值。

 
/**
     * 数组扩容检测
     * 属于ensureCapacity的非同步方法,在不产生成本的条件下进行集合扩容
     *
     * @see #ensureCapacity(int)
     */
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        // 使用减法避免int溢出问题
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
 /**
     * 集合扩容
     *
     * @param minCapacity 扩容要求最小长度
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 计算新的扩容长度 如果指定的扩容大小大于0 即扩大扩容大小 否则扩容增加原始大小 所以Vector默认扩容为原来的两倍
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                capacityIncrement : oldCapacity);
        // 比较新的扩容大小和扩容需求最小长度
        // 使用减法避免int溢出问题
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        // 扩容后大小超过MAX_ARRAY_SIZE
        // 使用减法避免int溢出问题
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            // 获取集合较大时的数组大小
            newCapacity = hugeCapacity(minCapacity);
        // 数据拷贝
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    /**
     * 数组长度较大时进行判断
     *
     * @param minCapacity 数组扩容最小要求长度
     * @return
     */
    private static int hugeCapacity(int minCapacity) {
        // 扩容长度小于0 int溢出
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        // 数组大于集合默认最大值 使用int最大值 否则使用集合默认最大值
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }

方法

add
  • public synchronized boolean add(E e)
    最集合最后位置添加一个元素
 /**
     * 在集合末尾添加元素
     *
     * @param e 添加的元素
     * @return {@code true} (as specified by {@link Collection#add})
     * @since 1.2
     */
    public synchronized boolean add(E e) {
        modCount++;
        // 确保容量
        ensureCapacityHelper(elementCount + 1);
        // 数据赋值 集合长度递增
        elementData[elementCount++] = e;
        return true;
    }
  • public void add(int index, E element)
    在指定位置添加一个元素
 /**
     * 在指定位置添加一个元素
     *
     * @param index   插入元素的指定位置
     * @param element 插入元素
     * @throws ArrayIndexOutOfBoundsException 指定位置不合法小于0或者大于集合长度
     * @since 1.2
     */
    public void add(int index, E element) {
        insertElementAt(element, index);
    }
addAll
  • public synchronized boolean addAll(Collection<? extends E> c)
    将指定集合中的元素全部加入到集合中
 /**
     * 将指定集合中的元素全部加入到集合中
     *
     * @param c 指定集合
     * @return 是否有新的元素加入集合
     * @throws NullPointerException 如果指定集合为null抛出此异常
     * @since 1.2
     */
    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;
    }
  • public synchronized boolean addAll(int index, Collection<? extends E> c)
    在指定位置插入指定集合
 /**
     * 在指定位置插入指定集合
     *
     * @param index 指定位置
     * @param c     指定集合
     * @return {@code true} if this Vector changed as a result of the call
     * @throws ArrayIndexOutOfBoundsException 如果指定位置不合法,指定位置小于0或者指定位置大于集合长度
     * @since 1.2
     */
    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;
    }
addElement

将指定元素插入集合尾部,在功能上和add(E)相同

/**
     * 将指定元素插入集合尾部
     * 此功能与{@link #add(E)}相同
     *
     * @param obj 插入集合的元素
     */
    public synchronized void addElement(E obj) {
        modCount++;
        // 容量检查
        ensureCapacityHelper(elementCount + 1);
        // 赋值
        elementData[elementCount++] = obj;
    }
capacity

获取集合数组可以容纳数量大小,和size()不同,因为集合会冗余一部分大小,这部分在该方法也是要显示的。

 /**
     * 获取数组当前容量
     */
    public synchronized int capacity() {
        return elementData.length;
    }
clear

删除集合中全部元素,removeAllElement是synchronized方法

   /**
     * 删除集合中全部元素
     *
     * @since 1.2
     */
    public void clear() {
        removeAllElements();
    }
clone

拷贝数组中的数据,对象还是原来的对象,操作数组中的对象是会想回影响的

 /**
     * 获取集合的拷贝
     * 如果集合中的元素并没有新建对象,所以改变集合中的元素会引起另一个集合元素改变
     *
     * @return a clone of this vector
     */
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
            Vector<E> v = (Vector<E>) super.clone();
            // 拷贝数据
            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);
        }
    }
contains

判断集合是否包含某个元素,虽然这个方法并不是同步的,但是indexOf却是同步的

/**
     * 判断集合是否包含某个元素
     *
     * @param o 是否包含的元素
     * @return {@code true} if this vector contains the specified element
     */
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

containsAll

是否包含指定集合全部元素

 /**
     * 获取是否包含指定集合全部元素
     *
     * @param c 指定集合
     * @return 是否包含指定集合全部元素
     * @throws NullPointerException 如果指定集合为null
     */
    public synchronized boolean containsAll(Collection<?> c) {
    // 调用AbstractCollection的containsAll方法
    
	// public boolean containsAll(Collection<?> c) {
	// 循环数组 判断有没有包含元素
	//    for (Object e : c)
	 //       if (!contains(e))
	 //           return false;
	 //   return true;
	}
        return super.containsAll(c);
    }
copyInto

将集合中的数据复制到指定数组中

 /**
     * 将集合中的数据复制到指定数组中
     *
     * @param anArray 复制数据的指定数组
     * @throws NullPointerException      如果指定数组为null抛出此异常
     * @throws IndexOutOfBoundsException 如果指定的数组无法完全容纳集合中的数据抛出此异常
     * @throws ArrayStoreException       如果数组类型和集合类型不一致
     * @see #toArray(Object[])
     */
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }
elementAt

获取指定位置的元素和get(int)功能一致

/**
     * 获取指定位置的元素
     * <p>
     * 这个方法在功能上和{@link #get(int)}相同
     *
     * @param index 指定位置
     * @return 指定位子的元素
     * @throws ArrayIndexOutOfBoundsException 如果指定位置超出集合抛出此异常
     */
    public synchronized E elementAt(int index) {
        // 判断位置合法
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }
        // 获取指定位置数据
        return elementData(index);
    }
elementData

获取指定位置元素,大部分都是内部在需要获取指定位置元素时都会调用这个方法

// 获取指定位置的元素
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }
elements

获取集合中数据枚举,使用匿名内部类实现Enumeration

 /**
     * 获取集合中数据枚举
     *
     * @return 获取集合中的枚举
     * @see Iterator
     */
    public Enumeration<E> elements() {
        return new Enumeration<E>() {
            // 当前访问位置
            int count = 0;

            /**
             * 是否由下一个元素
             * @return
             */
            public boolean hasMoreElements() {
                return count < elementCount;
            }

            /**
             * 获取元素
             * @return
             */
            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }
ensureCapacity

进行集合容量保证

 /**
     * 按照期望容量进行集合扩容
     * <p>
     * 尝试以期望的最小容量作为基础进行进行集合扩容
     *
     * @param minCapacity 期望的最小容量
     */
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }
equals

判断两个集合是否相同

 /**
     * 判断指定集合是否和当前集合想等
     *
     * @param o 指定结合
     * @return true if the specified Object is equal to this Vector
     */
    public synchronized boolean equals(Object o) {
    return super.equals(o);
//    public boolean equals(Object o) {
//        if (o == this)
//            return true;
//        if (!(o instanceof List))
//            return false;
//
//        ListIterator<E> e1 = listIterator();
//        ListIterator<?> e2 = ((List<?>) o).listIterator();
//        while (e1.hasNext() && e2.hasNext()) {
//            E o1 = e1.next();
//            Object o2 = e2.next();
//            if (!(o1==null ? o2==null : o1.equals(o2)))
//                return false;
//        }
 //       return !(e1.hasNext() || e2.hasNext());
 //   }
        
    }
firstElement

获取集合中第一个元素即get(0)或者elementAt(0)

 /**
     * 获取集合中第一个元素即get(0)或者elementAt(0)
     *
     * @return 集合的第一个元素
     * @throws NoSuchElementException 如果集合不包含任何元素
     */
    public synchronized E firstElement() {
        // 判断集合有没有元素
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        //返回第一个元素
        return elementData(0);
    }
forEach

循环调用指定某个操作

// 循环调用指定某个操作
    @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();
        }
    }
get

获取指定位置的元素

 /**
     * 获取指定位置的元素
     *
     * @param index 指定位置
     * @return 指定位置的元素
     * @throws ArrayIndexOutOfBoundsException 指定位置不合法小于0或者大于集合长度
     * @since 1.2
     */
    public synchronized E get(int index) {
        // 验证位置合法性
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        // 获取数据
        return elementData(index);
    }
hashCode

获取集合的hash值

/**
     * 返回集合的hash值.
     */
    public synchronized int hashCode() {
        return super.hashCode();
    }
indexOf
  • public int indexOf(Object o)
    获取指定元素第一次出现的位置
 /**
     * 获取指定元素第一次出现的位置
     *
     * @param o 指定元素
     * @return 指定元素的位置,如果指定元素不存在则返回-1
     */
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }
  • public synchronized int indexOf(Object o, int index)
    获取从开始位置开始第一次出现指定元素的位置
 /**
     * 获取从开始位置开始第一次出现指定元素的位置
     *
     * @param o     指定元素
     * @param index 开始位置
     * @return 指定元素的位置,如果指定元素不存在则返回-1
     * @throws IndexOutOfBoundsException 如果指定位置为负数
     * @see Object#equals(Object)
     */
    public synchronized int indexOf(Object o, int index) {
        if (o == null) {
            // 如果元素为null使用==进行比较
            for (int i = index; i < elementCount; i++)
                if (elementData[i] == null)
                    return i;
        } else {
            // 否则使用equasl进行比较
            for (int i = index; i < elementCount; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
insertElementAt

在指定位置插入元素,其后元素全部后移,功能上与add(int, E)相同

 /**
     * 在指定位置插入元素,其后元素全部后移
     * <p>
     * 功能上与{@link #add(int, E)}
     *
     * @param obj   插入的数据
     * @param index 指定位置
     * @throws ArrayIndexOutOfBoundsException 如果删除位置小于0或者超出数组
     */
    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        // 判断添加位置
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index
                    + " > " + elementCount);
        }
        // 容量检查
        ensureCapacityHelper(elementCount + 1);
        //  数据拷贝
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        // 赋值
        elementData[index] = obj;
        elementCount++;
    }
isEmpty

集合是否为空

 public synchronized boolean isEmpty() {
        return elementCount == 0;
    }

iterator

获取集合的迭代器

	/**
     * 获取集合的迭代器
     *
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public synchronized Iterator<E> iterator() {
        return new Itr();
    }
	/**
     * 迭代器实现
     */
    private class Itr implements Iterator<E> {
        // 下一个元素的下标
        int cursor;       // index of next element to return
        // 上一个返回元素的小标
        int lastRet = -1; // index of last element returned; -1 if no such
        // 期望修改值 用来实现fail-fast策略
        int expectedModCount = modCount;

        // 是否有下一个元素
        public boolean hasNext() {
            // Racy but within spec, since modifications are checked
            // within or after synchronization in next/previous
            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() {
            // 如果上次未返回或者已经被删除是为-1
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                // 检查修改
                checkForComodification();
                // 删除元素
                Vector.this.remove(lastRet);
                // 修改期望值
                expectedModCount = modCount;
            }
            // 修改下一个访问元素下标
            cursor = lastRet;
            // 修改上一个返回元素下标
            lastRet = -1;
        }

        // 循环调用指定某个操作
        @Override
        public void forEachRemaining(Consumer<? super E> action) {
            // 操作不能是null
            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();
        }
    }
lastElement

获取集合最后一个元素

 /**
     * 获取集合最后一个元素
     *
     * @return 集合的最有一个远古三
     * @throws NoSuchElementException 如果集合不包含任何元素抛出此异常
     */
    public synchronized E lastElement() {
        // 判断集合有没有元素
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        //返回最后一个元素
        return elementData(elementCount - 1);
    }
lastIndexOf
  • public synchronized int lastIndexOf(Object o)
    获取指定元素最后一次出现的位置
/**
     * 获取指定元素最后一次出现的位置
     *
     * @param o 指定元素
     * @return 指定最后元素的位置,如果指定元素不存在则返回-1
     */
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount - 1);
    }

-public synchronized int lastIndexOf(Object o, int index)
获取从指定位置之前指定元素最后一次出现的位置

/**
     * 获取从指定位置之前指定元素最后一次出现的位置
     *
     * @param o     指定元素
     * @param index 指定位置
     * @return 指定最后元素的位置,如果指定元素不存在则返回-
     * @throws IndexOutOfBoundsException 如果指定位置大于等于集合数量
     */
    public synchronized int lastIndexOf(Object o, int index) {
        // 判断指定位置
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= " + elementCount);

        // 判断元素位置
        if (o == null) {
            // 如果元素为null使用==进行比较
            for (int i = index; i >= 0; i--)
                if (elementData[i] == null)
                    return i;
        } else {
            // 否则使用equasl进行比较
            for (int i = index; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
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;
        }
    }

    // 循环调用指定某个操作
    @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();
        }
    }

  • public synchronized ListIterator listIterator(int index)
    获取从开始位置的列表迭代器

    /**
     * 获取从开始位置的列表迭代器
     *
     * @see #listIterator(int)
     */
    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

  • public synchronized ListIterator listIterator(int index)
    从指定位置获取列表迭代器
 /**
     * 从指定位置获取列表迭代器
     *
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public synchronized ListIterator<E> listIterator(int index) {
        // 验证指定位置
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: " + index);
        return new ListItr(index);
    }

readObject

读取流中的数据 反序列化

/**
     *
     * 读取流中的数据 反序列化
     * @param in the stream
     * @throws java.io.IOException    if an I/O error occurs
     * @throws ClassNotFoundException if the stream contains data
     *                                of a non-existing class
     */
    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();
    }
remove
  • public synchronized E remove(int index)
    删除指定位置的元素,后面元素需要往前移动
/**
     * 删除指定位置的元素,后面元素需要往前移动
     *
     * @param index 删除的指定位置
     * @return 被删除的数据
     * @throws ArrayIndexOutOfBoundsException 指定位置不合法小于0或者大于集合长度
     * @since 1.2
     */
    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)
            // 移动元素数量大于0进行数组数据移动
            System.arraycopy(elementData, index + 1, elementData, index,
                    numMoved);
        // 数组末尾设为null
        elementData[--elementCount] = null; // Let gc do its work

        return oldValue;
    }
  • public boolean remove(Object o)
  /**
     * 删除集合中第一次出现的指定元素
     *
     * @param o 指定元素
     * @return 如果包含此元素(删除成功)返回true
     * @since 1.2
     */
    public boolean remove(Object o) {
        return removeElement(o);
    }
removeAll

删除指定集合中全部元素

  /**
     * 删除指定集合中全部元素
     *
     * @param c 指定集合
     * @return 是否删除集合中的元素
     * @throws ClassCastException   如果删除集合中的元素和集合的类型不同
     * @throws NullPointerException 如果指定集合中包含null,但是指定集合不支持null值
     * @since 1.2
     */
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
        //迭代器调用删除
      //  public boolean removeAll(Collection<?> c) {
      //  Objects.requireNonNull(c);
      //  boolean modified = false;
      //  Iterator<?> it = iterator();
      //  while (it.hasNext()) {
      //      if (c.contains(it.next())) {
      //          it.remove();
      //         modified = true;
      //    }
      //  }
      //  return modified;
    //}
    }
removeAllElements

删除集合中所有元素

 /**
     * 删除集合中所有元素
     * 此功能与{@link #clear}相同
     */
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }
removeElement

删除集合中的指定元素

 /**
     * 删除集合中的指定元素
     * 此功能与{@link #remove(Object)}相似
     *
     * @param obj 删除的元素
     * @return 是否删除成功
     */
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        // 元素所在位置
        int i = indexOf(obj);
        if (i >= 0) {
            // 按位置删除元素
            removeElementAt(i);
            return true;
        }
        return false;
    }
removeElementAt

删除指定位置的元素,删除之后所有元素左移,并且集合长度减一

 /**
     * 删除指定位置的元素,删除之后所有元素左移,并且集合长度减一
     * <p>
     * 其功能类似 {@link #remove(int)}
     *
     * @param index 删除元素的指定位置
     * @throws ArrayIndexOutOfBoundsException 如果删除位置小于0或者超出数组
     */
    public synchronized void removeElementAt(int index) {
        modCount++;
        // 判断删除位置
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    elementCount);
        } else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        // 判断移动元素数量
        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 */
    }
removeIf

删除满足条件的集合元素

//删除满足条件的集合元素
    @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;
        // 使用BitSet对象记录要移除元素的下标
        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)) {
                // 满足条件 删除数量+1
                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开始 返回位置为false的第一个索引
                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;
    }
removeRange

移除从开始位置(包括)到结束位置(不包括)的全部元素

  /**
     * 移除从开始位置(包括)到结束位置(不包括)的全部元素
     */
    protected synchronized void removeRange(int fromIndex, int toIndex) {
        modCount++;
        // 计算移动数量
        int numMoved = elementCount - toIndex;
        // 数组前移
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                numMoved);

        // 计算数组长度
        int newElementCount = elementCount - (toIndex - fromIndex);
        // Let gc do its work
        // 多元素置为null
        while (elementCount != newElementCount)
            elementData[--elementCount] = null;
    }
replaceAll

执行替换操作

 // 执行替换操作
    @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++;
    }
retainAll
 /**
     * 删除不在指定集合中的元素(交集)
     *
     * @param c 指定集合
     * @return true if this Vector changed as a result of the call
     * @throws ClassCastException   指定集合中的元素类型和集合的类型不兼容
     * @throws NullPointerException 如果指定集合中包含null,但是指定集合不支持null值
     * @since 1.2
     */
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
        // 迭代起循环删除
       // public boolean retainAll(Collection<?> c) {
       //Objects.requireNonNull(c);
       // boolean modified = false;
       // Iterator<E> it = iterator();
       // while (it.hasNext()) {
       //     if (!c.contains(it.next())) {
       //         it.remove();
       //         modified = true;
       //    }
       // }
        return modified;
    }
    }
set

替换指定位置元素

/**
     * 替换指定位置元素
     *
     * @param index   指定位置
     * @param element 替换元素
     * @return 被替换的数据
     * @throws ArrayIndexOutOfBoundsException 指定位置不合法小于0或者大于集合长度
     * @since 1.2
     */
    public synchronized E set(int index, E element) {
        // 验证替换位置合法性
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        // 获取原始数据
        E oldValue = elementData(index);
        // 替换数据
        elementData[index] = element;
        return oldValue;
    }
setElementAt
 /**
     * 将指定位置的元素替换掉,原来的元素抛弃
     * <p>
     * <p>
     * 者个方法在功能上和{@link #set(int, E)}相同
     *
     * @param obj   替换数据
     * @param index 替换位置
     * @throws ArrayIndexOutOfBoundsException 替换位置小于0或者替换位置超出数组
     */
    public synchronized void setElementAt(E obj, int index) {
        // 判断为止
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    elementCount);
        }
        // 替换元素
        elementData[index] = obj;
    }

setSize

设置集合大小,会改变数组的大小,多余的数据会删除掉

/**
     * 设置集合大小
     *
     * @param newSize 新集合大小
     * @throws ArrayIndexOutOfBoundsException 设置大小为负数抛出此异常
     */
    public synchronized void setSize(int newSize) {
        modCount++;
        // 比较设置到校和集合原来大小
        if (newSize > elementCount) {
            // 如果集合设置大小大于原始大小进行扩容及数据拷贝到扩容后的数组中
            ensureCapacityHelper(newSize);
        } else {
            // 否则将集合超出部分的数据设置为null
            for (int i = newSize; i < elementCount; i++) {

                elementData[i] = null;
            }
        }
        //修改集合大小为设置大小
        elementCount = newSize;
    }
size

获取集合长度

/**
     * 获取集合长度
     */
    public synchronized int size() {
        return elementCount;
    }
sort

集合排序

 // 集合排序
    @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++;
    }
spliterator

获取集合分割迭代器


    /**
     * 获取集合分割迭代器
     *
     * @return a {@code Spliterator} over the elements in this list
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new VectorSpliterator<>(this, null, 0, -1, 0);
    }

    /**
     * 分割迭代器实现
     */
    static final class VectorSpliterator<E> implements Spliterator<E> {
        // 原始集合
        private final Vector<E> list;
        // 数组 集合在第一次调用的时候 为null 在调用VectorSpliterator中的方法后会把变为集合的数组
        private Object[] array;
        // 开始位置 在trySplit和tryAdvance都会修改
        private int index; // current index, modified on advance/split
        // 结束位置 集合在第一次调用的时候 为-1 在调用VectorSpliterator中的方法后会把变为集合的长度
        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;
        }

       // 获取fence值 即集合结束值
        private int getFence() { // initialize on first use
            int hi;
            // 如果集合截数据小于0
            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();

            // 集合不为null
            if ((lst = list) != null) {
                if ((hi = fence) < 0) {
                    // 集合结束位置小于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);
        }

        //返回当前对象有哪些特征值
        // ORDERED 元素之间是有顺序的
        // SIZED 表示长度为有限个
        // SUBSIZED 迭代器所分割得到的子迭代器也是有序的
        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
subList

返回从开始位置(包括)到结束位置(不包括)的元素集合

/**
     * 返回从开始位置(包括)到结束位置(不包括)的元素集合
     *
     *
     * @param fromIndex 开始位置
     * @param toIndex   结束为止
     * @return a view of the specified range within this List
     * @throws IndexOutOfBoundsException 开始位置小于0或者结束位置超过数组长度
     * @throws IllegalArgumentException  如果开始位置大约结束为止
     */
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        // 使用Collections.synchronizedList实现
        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
                this);
    }
toArray
  • public synchronized Object[] toArray()
    获取集合中所有元素组成的数组
/**
     * 获取集合中所有元素组成的数组
     *
     * @since 1.2
     */
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }
  • public synchronized T[] toArray(T[] a)
    按照指定类型数组获取集合中所有元素
 /**
     * 按照指定类型数组获取集合中所有元素
     *
     * @param a 指定类型数组
     * @throws ArrayStoreException  指定数组类型不是集合元素的类型或者父类型
     * @throws NullPointerException 给定数组为空
     * @since 1.2
     */
    @SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
        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;

        return a;
    }
toString

重写toString方法

/**
     * 重写toString方法
     */
    public synchronized String toString() {
        return super.toString();
    }
trimToSize

修剪数组的大小至真实的大小

/**
     * 修剪数组的大小至真是的大小
     * 在创建或者扩容时 数组会留一部分冗余容量,此方法可以删除绒绒量
     */
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }
writeObject

将集合写入流中 序列化

 * 将集合写入流中 序列化
     */
    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();
    }

结束语

Vector和ArrayList功能几乎一样,但是其为线程安全的。整体功能和Coolection.SynchronizedRandomAccessList类似。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值