Java集合源码分析(八)-Vector(上)

113 阅读17分钟

「这是我参与2022首次更文挑战的第13天,活动详情查看:2022首次更文挑战

源码

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

    /**
     * 从 JDK 1.0.2 使用 serialVersionUID 实现互操作性
     */
    private static final long serialVersionUID = -2767605614048989439L;
    /**
     * 分配数组的最大长度
     * 一些虚拟机保留一些头字在数组中
     * 尝试分配更大数组可能导致 OutOfMemoryError:请求数组长度超出虚拟机限制
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    /**
     * 存储 Vector 组件的数组缓存
     *
     * Vector 的容量时这个数组缓存的长度,并且 Vector 的容量至少足够大包含 Vector 的元素
     *
     * Vector 最后一个元素后面的任何数组元素都是 null
     */
    protected Object[] elementData;
    /**
     * 这个 Vector 对象有效组件的数量
     * 组件 elementData[0] 到 elementData[elementCount-1] 是实际项目
     */
    protected int elementCount;

    /**
     * 当 Vector 的大小大于它的容量时,它的容量自动增加
     * 如果容量增加少于等于 0,当 Vector 每次需要增长时,容量翻倍
     */
    protected int capacityIncrement;

    /**
     * 通过指定初始化容量和容量增长构建一个空的 Vector
     *
     * @param initialCapacity   Vector 的初始化容量
     * @param capacityIncrement 当 Vector 溢出时增加容量的数量
     * @throws IllegalArgumentException 如果指定初始化容量是负的
     */
    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 容量增长构建一个空的 Vector
     *
     * @param initialCapacity Vector 的初始化容量
     * @throws IllegalArgumentException 如果指定初始化容量是负的
     */
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    /**
     * 构造一个空的 Vector,它的内部数据数组大小为 10,它标准容量增加是 0
     */
    public Vector() {
        this(10);
    }

    /**
     * 构造一个 Vector 包含指定集合的元素,按照集合的迭代器返回的顺序
     *
     * @param c 要将元素放入这个 Vector 的集合
     * @throws NullPointerException 如果指定集合是
     * @since 1.2
     */
    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray 可能(错误地)不会返回 Object[] (看 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

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

    /**
     * 复制这个 Vector 的部分到指定的集合
     * 这个 Vector 索引 k 上的内容被复制到 anArray 的 k 部分中
     *
     * @param anArray 组件被复制到数组
     * @throws NullPointerException      如果给定数组是 null
     * @throws IndexOutOfBoundsException 如果指定数组没有足够大容纳这个 Vector 的所有内容
     * @throws ArrayStoreException       如果这个 Vector 的组件不是能够存储在指定数组的运行时类型
     * @see #toArray(Object[])
     */
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }

    /**
     * 修剪这个 Vector 的容量成为 Vector 的当前大小
     * 如果这个 Vector 容量大于它当前的大小,然后通过替代它内部数据数组,改变容量等于它内部数据数组的大小,通过一个较小的值保存在 elementData 字段
     * 应用可以使用这个操作最小化 Vector 的存储
     */
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }

    /**
     * 增加这个 Vector 的容量,如果必要的话,确认它至少可以容纳最小容量参数指定的组件数量
     *
     * 如果这个 Vector 的当前容量小于 minCapacity,然后通过替代它的内部数据数组增加它容量,通过一个较大的值保存在 elementData 字段
     * 新数据数组的大小是将旧大小加上 capacityIncrement,除非 capacityIncrement 的值是小于或者等于 0,在那种情况下,新容量将是旧容量的两倍;
     * 但是如果这个新大小依然小于 minCapacity,然后这个新容量将变为  minCapacity
     *
     * @param minCapacity 期望最小的容量
     */
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

    /**
     * 这个实现 ensureCapacity 非同步语义
     * 这个类的同步方法能够在内部调用这个方法确保容量,而不会产生额外的同步成本
     *
     * @see #ensureCapacity(int)
     */
    private void ensureCapacityHelper(int minCapacity) {
        // 有溢出意识的代码
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    /**
     * 设置这个 Vector 的大小
     * 如果新大小大于当前大小,添加新 null 项到 Vector 的末尾
     * 如果新大小小于当前大小,丢弃索引 newSize 和更高的所有组件
     *
     * @param newSize 这个 Vector 的新大小
     * @throws ArrayIndexOutOfBoundsException 如果新大小时负的
     */
    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;
    }

    /**
     * 返回这个 Vector 当前容量
     *
     * @return 当前容量(它内部数据数组的长度,保持这个 Vector 的 elementData 字段)
     */
    public synchronized int capacity() {
        return elementData.length;
    }

    /**
     * 返回这个 Vector 组件的数量
     *
     * @return 这个 Vector 组件的数量
     */
    public synchronized int size() {
        return elementCount;
    }

    /**
     * 测试这个 Vector 是否没有组件
     *
     * @return {@code true} 当且仅当这个 Vector 没有组件,也就是说,它的大小是 0;
     * {@code false} 否则.
     */
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }

    /**
     * 返回这个 Vector 组件的枚举
     * 返回的 Enumeration 对象将生成这个 Vector 的全部项
     * 第一个项是索引 0 生成的项,然后在索引 1 的项,以此类推
     *
     * @return 这个 Vector 组件的枚举
     * @see Iterator
     */
    public Enumeration<E> elements() {
        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");
            }
        };
    }

    /**
     * 如果这个 Vector 包含指定元素,返回 true
     * 更准确的说,当且仅当这个 Vector 包含至少一个元素 e 满足 (o==null && e==null && o.equals(e)),返回 true
     *
     * @param o 要测试是否在这个 Vector 存在的元素
     * @return {@code true} 如果这个 Vector 包含指定元素
     */
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    /**
     * 返回指定元素在这个 Vector 第一次出现索引,如果这个 Vector 没有包含元素返回 -1
     * 更正确的说,返回最低索引 i,例如 (o==null && get(i)==null && o.equals(get(i))),如果这里没有这样的索引,返回 -1
     *
     * @param o 要搜索的元素
     * @return the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element
     */
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    /**
     * 返回这个 Vector 指定元素第一次出现的索引,使用 index 向前搜索,或者当这个元素没有找到的时候返回 -1
     * 更正确的说,返回最低索引 i,例如 (i >= index && (o==null ? get(i)==null : o.equals(get(i)))),如果这里没有这样的索引,返回 -1
     *
     * @param o     要搜索的元素
     * @param index 开始搜索的索引
     * @return 这个 Vector 元素第一次出现在 index 位置或者更后的索引
     * {@code -1} 如果元素没有找到
     * @throws IndexOutOfBoundsException 如果指定索引是负的
     * @see Object#equals(Object)
     */
    public synchronized int indexOf(Object o, int index) {
        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;
        }
        return -1;
    }

    /**
     * 返回指定元素在这个 Vector 最后一次出现的索引,否则返回 -1,如果这个 Vector 没有包含这个元素
     * 更正确的说,返回最高的索引 i,例如 (o==null ? get(i)==null : o.equals(get(i))),或者 -1,如果没有这样的索引
     *
     * @param o 要搜索的元素
     * @return 指定元素在这个 Vector 最后一次出现的索引,如果这个 Vector 没有包含这个元素,则为 -1
     */
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount - 1);
    }

    /**
     * 返回指定元素在这个 Vector 最后一次出现的索引,从 index 向后查找,否则返回 -1,如果这个 Vector 没有包含这个元素
     * 更正确的说,返回最高的索引 i,例如 (i <= index && (o==null ? get(i)==null : o.equals(get(i)))),或者 -1,如果没有这样的索引
     *
     * @param o     要搜索的元素
     * @param index 开始向后查找的索引
     * @return 元素在这个 Vector 中小于或等于 index 位置最后一次出现索引
     * -1 如果没有找到元素
     * @throws IndexOutOfBoundsException 如果指定索引大于或或等于这个 Vector 当前大小
     */
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= " + elementCount);

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

    /**
     * 返回指定索引的组件
     *
     * 这个方法在功能上和 #get(int) 方法(List 接口的一部分)是相同的
     *
     * @param index 这个 Vector 的索引
     * @return 指定索引的组件
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围 (index < 0 || index >= size())
     */
    public synchronized E elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }

        return elementData(index);
    }

    /**
     * 返回这个 Vector 的第一个组件(索引 0 的项)
     *
     * @return 这个 Vector 的第一个组件
     * @throws NoSuchElementException 如果这个 Vector 没有组件
     */
    public synchronized E firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    /**
     * 返回 Vector 最后的组件
     *
     * @return Vector 最后的组件,即在索引 size()-1 组件
     * @throws NoSuchElementException 如果这个 Vector 是空
     */
    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }

    /**
     * 将这个 Vector 的指定 index 的组件设置为指定对象
     * 这个位置的前一个组件将丢弃
     *
     * 索引必须大于或等于 0,并且小于 Vector 当前的大小
     *
     * 这个方法在功能上和 #set(int, Object) 方法(List 接口的一部分)是相同的
     * 注意,set 方法反转了参数的顺序,更紧密匹配数组的使用
     * 还要注意,set 方法返回存储在指定位置的旧值
     *
     * @param obj   组件将被设置为什么
     * @param index 指定索引
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围(index < 0 || index >= size())
     */
    public synchronized void setElementAt(E obj, int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    elementCount);
        }
        elementData[index] = obj;
    }

    /**
     * 删除指定索引的组件
     * 这个 Vector 索引大于或等于指定 index 的每一个组件下移,使得索引小于之前的值
     * 这个 Vector 大小减少了 1
     *
     * 索引必须大于或等于 0,并且小于 Vector 当前大小
     *
     * 这个方法在功能上和 #remove(int) 方法(List 接口的一部分)是相同的
     * 注意,remove 方法返回存储在指定位置的旧值
     *
     * @param index 移除对象的索引
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围(index < 0 || index >= size())
     */
    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);
        }
        elementCount--;
        elementData[elementCount] = null; /* 让gc完成它的工作 */
    }

    /**
     * 在这个 Vector 指定 index 插入指定对象作为组件
     * 这个 Vector 索引大于或等于指定 index 的每个组件上移,使得索引大于之前的值
     *
     * 索引必须大于或等于 0,并且小于 Vector 当前大小(如果索引等于 Vector 当前大小,新元素追加到 Vector)
     *
     * 这个方法在功能上和 #add(int, Object) 方法(List 接口的一部分)是相同的
     * 注意,add 方法反转了参数的顺序,更紧密匹配数组的使用
     *
     * @param obj   插入的组件
     * @param index 插入新组件的位置
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围(index < 0 || index >= size())
     */
    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++;
    }
    /**
     * 添加指定组件到这个 Vector 的结尾,将它的大小增加一
     * 这个 Vector 的容量增加,如果它的大小大于它的容量
     *
     * 这个方法在功能上和 #add(Object) 方法(List 接口的一部分)是相同的
     *
     * @param obj 添加的组件
     */
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

    /**
     * 从这个 Vector 移除参数第一个(最低索引)出现
     * 如果对象在这个 Vector 被找到,这个 Vector 每一个索引大于或等于对象的索引的组件下一,使得索引小于之前的值
     *
     * 这个方法在功能上和 #remove(Object) 方法(List 接口的一部分)是相同的
     *
     * @param obj 移除的组件
     * @return {@code true} 如果参数时这个 Vector 的一部分; {@code false} 否则
     */
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    /**
     * 从这个 Vector 移除全部组件,并且设置它的大小为 0
     * <p>
     * 这个方法在功能上和 clear 方法(List 一部分)是相同的
     */
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

    /**
     * 返回这个 Vector 的克隆对象
     * 这个克隆对象将包含内部数据数组克隆的引用,不是这个 Vector 对象的原始内部数据数组引用
     *
     * @return 这个 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);
        }
    }

    /**
     * 返回按正确顺序包含这个 Vector 的全部元素的数组
     *
     * @since 1.2
     */
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

    /**
     * 返回按正确顺序包含这个 Vector 元素的数组;返回数组的运行时类型是指定数组的运行时类型
     * 如果 Vector 适合指定数组,返回这个数组
     * 否则,使用指定数组的运行时类型和这个 Vector 的大小分配一个新数组
     *
     * 如果 Vector 适合指定数组,并且有剩余空间(即,数组中的元素比 Vector 中的元素多),数组中紧随 Vector 结束的元素设置为 null
     * (只有当调用者知道 Vector 没有包含任何 null 元素,才有助于确定 Vector 的长度)
     *
     * @param a  如果它足够大将 Vector 元素存储到的数组,否则,分配一个相同运行时类型的新数组
     * @return 包含 Vector 元素的数组
     * @throws ArrayStoreException  如果 a 的运行时类型不是这个 Vector 每个元素的运行时类型的父类
     * @throws NullPointerException 如果给定数组是 null
     * @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);

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

        return a;
    }

    // 位置访问操作

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * 返回这个 Vector 指定位置的元素
     *
     * @param index 要返回元素的索引
     * @return 再指定索引的对象
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围(index < 0 || index >= size())
     * @since 1.2
     */
    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    /**
     * 使用指定元素代替这个 Vector 指定位置元素
     *
     * @param index   替换元素的索引
     * @param element 存储指定位置的元素
     * @return 指定位置之前的元素
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围 (index < 0 || index >= size())
     * @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;
    }

    /**
     * 追加指定元素到这个 Vector 的末尾
     *
     * @param e 要追加到这个 Vector 的元素
     * @return {@code true} (像 Collection#add 描述)
     * @since 1.2
     */
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

    /**
     * 移除指定元素在这个 Vector 的第一次出现
     * 更正确的说,移除最低索引 i 的元素(o==null ? get(i)==null : o.equals(get(i)))(如果这样的元素存在)
     *
     * @param o 从这个 Vector 移除的元素,如果存在
     * @return true 如果 Vector 包含指定元素
     * @since 1.2
     */
    public boolean remove(Object o) {
        return removeElement(o);
    }

    /**
     * 插入指定元素到这个 Vector 的指定位置
     * 右移(增加它们的索引)当前位置的元素(如果有)和任何后续元素
     *
     * @param index 插入指定元素的索引
     * @param element 插入的元素
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围(index < 0 || index > size())
     * @since 1.2
     */
    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    /**
     * 移除这个 Vector 指定位置的元素
     * 左移后续任何元素(从它们的索引减一)
     * 返回被 Vector 移除的元素
     *
     * @param index 要被移除的元素的索引
     * @return 被移除的元素
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围( index < 0 || index >= size())
     * @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)
            System.arraycopy(elementData, index + 1, elementData, index,
                    numMoved);
        elementData[--elementCount] = null; // Let gc do its work

        return oldValue;
    }

    /**
     * 从这个 Vector 移除全部元素
     * 这个调用返回后,这个 Vector 将变成空(除非它抛出异常)
     *
     * @since 1.2
     */
    public void clear() {
        removeAllElements();
    }

    // 批量操作

    /**
     * 返回 true,如果这个 Vector 包含指定集合的全部元素
     *
     * @param c 元素将测试在这个 Vector 是否包含的集合 a collection whose elements will be tested for containment in this Vector
     * @return true 如果这个 Vector 包含指定集合的全部元素
     * @throws NullPointerException 如果指定集合是 null
     */
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    /**
     * 追加指定集合的全部元素到这个 Vector 的末尾,按照指定集合的迭代器返回的顺序
     * 如果操作期间修改了指定集合,这个操作的行为是未定义的(这意味着,如果指定集合是这个 Vector,并且这个 Vector 是非空的,这个调用的行为是未定义的)
     *
     * @param c 插入这个 Vector 的元素
     * @return {@code true} 如果这个 Vector 因为调用这个方法改变
     * @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;
    }

    /**
     * 从这个 Vector 移除移除指定集合包含的所有元素
     *
     * @param c 从 Vector 移除元素的集合
     * @return true 如果这个 Vector 因为调用这个方法改变
     * @throws ClassCastException   如果这个 Vector 的一个或多个元素的类型与指定集合不相容
     * @throws NullPointerException 如果这个 Vector 包含一个或多个 null 元素,并且指定集合不支持 null 元素,或者指定集合是 null
     * @since 1.2
     */
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    /**
     * 只保留这个 Vector 包含指定集合的元素
     * 换句话说,从这个 Vector 移除全部指定集合不包含的元素
     *
     * @param c 要保留在这个 Vector 元素的集合(全部其他元素移除)
     * @return true 如果这个 Vector 因为调用这个方法改变
     * @throws ClassCastException   如果这个 Vector 的一个或多个元素的类型与指定集合不相容
     * @throws NullPointerException 如果这个 Vector 包含一个或者多个 null 值,并且指定集合不支持 null 元素,或者指定集合是 null
     * @since 1.2
     */
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

    /**
     * 插入指定集合的所有元素到这个 Vector 指定的位置
     *
     * 右移(增加它们的索引)当前位置的元素(如果有)和任何后续元素
     * 新元素将按指定集合迭代器返回的顺序出现在 Vector
     *
     * @param index 从指定集合插入第一个元素的索引
     * @param c     要插入到这个 Vector 的元素
     * @return {@code true} 如果这个 Vector 因为调用这个方法改变
     * @throws ArrayIndexOutOfBoundsException 如果索引超出范围( index < 0 || index > size())
     * @throws NullPointerException           如果指定集合是 null
     * @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;
    }

    /**
     * 比较指定对象和这个 Vector 是否相等
     * 返回 true,当且仅当指定对象同样是一个列表,两个列表有相同大小,并且两个列表的元素对都是相等的(两个元素 e1 和 e2 是相等,如果 (e1==null ? e2==null : e1.equals(e2))}.)
     * 换句话说,两个列表定义相同,如果它们以相同顺序包含相同元素
     *
     * @param o 与这个 Vector 进行相等比较的对象
     * @return true 如果指定对象与这个列表相同
     */
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }

    /**
     * 返回这个 Vector 的哈希码值
     */
    public synchronized int hashCode() {
        return super.hashCode();
    }

    /**
     * 返回这个 Vector 的字符串表示形式,包含每个元素的字符串表示形式
     */
    public synchronized String toString() {
        return super.toString();
    }

    /**
     * 返回这个列表指定从 fromIndex(包括) 到 toIndex(不包括)区域之间部分的视图(如果 fromIndex 和 toIndex 相等,返回的列表是空)
     * 返回的列表是基于这个列表,所以返回列表的的改变是这个列表支持的重新操作
     *
     * 这个方法不需要明确操作范围(数组通常存在的那种排序)
     * 通过操作子列表视图而不是整个列表,任何需要列表操作可以被用作范围操作
     * 例如,下面的语法从列表移除一系列元素
     * <pre>
     *      list.subList(from, to).clear();
     * </pre>
     * 类似的语法也可用于 indexOf 和 lastIndexOf,和 Collections 类的全部算法能够应用于子列表
     *
     * 如果支持列表(即,这个列表)在结构上改变,而不是通过返回的列表,这个方法返回的列表的语义变成未定义(结构改变会改变列表的大小,或者用某种方式干扰它,正在迭代可能产生错误的结果)
     *
     * @param fromIndex 子列表的起点(包括)
     * @param toIndex   子列表的终点(不包括)
     * @return a 这个列表指定范围的视图
     * @throws IndexOutOfBoundsException 如果端点索引值超出范围(fromIndex < 0 || toIndex > size)
     * @throws IllegalArgumentException  如果端点索引值超出顺序(fromIndex > toIndex)
     */
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);
    }

    /**
     * 从这个列表移除所有索引在 fromIndex(包括)和 toIndex(不包括) 元素
     * 左移任何后续元素(减少他们的索引)
     * 这个调用通过 (toIndex - fromIndex) 元素缩短列表(如果 toIndex==fromIndex,这个操作没有影响)
     */
    protected synchronized void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = elementCount - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                numMoved);

        // 让 gc 完成它的工作
        int newElementCount = elementCount - (toIndex - fromIndex);
        while (elementCount != newElementCount)
            elementData[--elementCount] = null;
    }

    /**
     * 从流中加载 Vector 实例(也就是说,反序列化它)
     * 这个方法执行检查确保字段的一致性
     *
     * @param in 流
     * @throws java.io.IOException    如果 I/O 异常发生
     * @throws ClassNotFoundException 如果流包含不存在类的数据
     */
    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();
    }

    /**
     * 保存 Vector 实例的状态到流中(也就是说,序列化它)
     * 这个方法同步执行确保序化数据的一致性
     */
    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#next 返回指定索引指明的第一个元素
     * 初始化调用 ListIterator#previous 返回指定索引为负一的元素
     *
     * 返回的列表迭代器是快速失败
     *
     * @throws IndexOutOfBoundsException
     */
    public synchronized ListIterator<E> listIterator(int index) {
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: " + index);
        return new ListItr(index);
    }

    /**
     * 返回这个列表的元素的列表迭代器(按正确的顺序)
     * <p>
     * 返回的列表迭代器是快速失败
     *
     * @see #listIterator(int)
     */
    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 返回按正确的顺序遍历这个列表的元素的迭代器
     * <p>
     * 返回的迭代器是快速失败
     *
     * @return 按正确顺序遍历这个列表的元素的迭代器
     */
    public synchronized Iterator<E> iterator() {
        return new Itr();
    }

    @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);
        // 找出在筛选器断言阶段移除哪些元素抛出的任何异常将使集合不可变
        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;  // 让 gc 完成它的工作
            }
            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++;
    }

    /**
     * 在这个列表的元素上创建一个延迟绑定和快速失败的分离器
     * <p>
     * 分离器报告 Spliterator#SIZED,Spliterator#SUBSIZED 和  Spliterator#ORDERED
     * 重写实现应该记录额外特征值的报告
     *
     * @return 这个列表的元素的分离器
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new VectorSpliterator<>(this, null, 0, -1, 0);
    }

    /**
     * 类似 ArrayList 分离器
     */
    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 = 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; // 提升从循环进入和检查
            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;
        }
    }

    /**
     * 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;
        }

        @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 的优化版本
     */
    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;
        }
    }
}