List接口 — Vector类源码分析

Vector的源码理解起来不难,Vector是由数组来实现的,对于增删改查也是数组的相关操作
源码中只保留了重要的代码,删去了部分代码(包的导入与英文注释)

Vector类的声明1

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

继承了AbstractList抽象类(实现了List接口,拥有增删查改等方法);Vector 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。
Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。


Vector类的字段

	// 核心: 用来保存数据的数组,类型为Object,所以可以存储任意类型的数据
    protected Object[] elementData;
    // 核心: elementData数组的实际容量
    protected int elementCount;
 	// 添加数据若需要扩容时的容量自动增加的一个量
    protected int capacityIncrement;
	// 官方解释:使用JDK 1.0.2中的序列化版本uid实现互操作性 
    private static final long serialVersionUID = -2767605614048989439L;

	// 并未在Vector类中出现,继承了父类AbstractList中的字段
	// 已从结构上修改 此列表的次数。
	// 从结构上修改是指更改列表的大小,或者打乱列表,从而使正在进行的迭代产生错误的结果。
	protected transient int modCount = 0;

Vector类的四个构造函数

	/**
	* 使用指定的初始通量和容量增量构造一个空的向量
	* 
	* @param initialCapacity 向量的初始容量
	* @param capacityIncrement 当向量溢出时,容量增加的数量
	*/
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        // 自己在构造方法时一定要考虑这种特殊情况,来防止意外发生
        if (initialCapacity < 0) 
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
     	// 直接new一个Object类型数组,数组大小即为第一个入参的值
        this.elementData = new Object[initialCapacity]; 
        // 设置容量增长的大小
        this.capacityIncrement = capacityIncrement;
    }

 
    public Vector(int initialCapacity) {
        this(initialCapacity, 0); // 调用上一个构造函数,只是把向量增量设置为1
    }


    public Vector() {
        this(10); // 调用上一个构造函数,对于new一个无参的Vector对象,默认设置数组大小为10
    }

	/**
	* 将集合元素按照顺序复制到elementData数组中
	* 
	* @param Collection<? extends E> c 要复制的集合
	*/
    public Vector(Collection<? extends E> c) {
    	// 获取集合c转换为数组后赋值给elementData
        elementData = c.toArray(); 
        // 设置数组的长度
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

Vector类方法的辅助方法(不可调用)

 	/** 当添加元素时会先调用这个方法,来确认容量的大小是否能够继续添加元素
 	*
 	* @param minCapacity 这个参数的值为 elementCount + 1,即数组的元素个数+1
 	*/
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

	// 若数组元素添加一个元素后的大小比数组的长度 大时,那么就需要增加数组的长度,否则将会出现数组越界异常
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

   // 要分配的数组的最大大小
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

	// 增加数组的长度
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length; // 原数组的长度
        // 若没有设置向量增长系数(即new对象时没有调用第一个构造函数),那么默认增加为该数组两倍的大小
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ? // 是否设置了向量增长系数
                                         capacityIncrement : oldCapacity);
    	// 假设newCapacity的大小为2*oldCapacity即两倍的数组的长度.
    	// 若两倍数组长度大于数组长度+1,那么该数组大小直接为数组长度加1的大小,并不会增加无用的数组长度.
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity; 
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

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

Vector类的API

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

	// 若数组的大小比实际的元素的个数大,将会通过复制的方式来赋给一个只包含元素的数组
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }
 
 	// 设置此向量的大小
    public synchronized void setSize(int newSize) {
        modCount++;
        // 新大小 > 当前大小,会创建一个新的长度的数组
        if (newSize > elementCount) {
            ensureCapacityHelper(newSize);
        } else { // 如果新大小小于当前大小,则丢弃索引 newSize 处及其之后的所有项
            for (int i = newSize ; i < elementCount ; i++) {
                elementData[i] = null;
            }
        }
        // 数组的大小等于设置的新大小
        elementCount = newSize;
    }

   // 返回数组的长度
    public synchronized int capacity() {
        return elementData.length;
    }

   	// 返回数组的实际大小(即数组元素的个数)
    public synchronized int size() {
        return elementCount;
    }

    // 判断数组是否含有元素										
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }

  	// 返回此向量的组件的枚举。
  	// 返回的枚举对象将生成该向量中的所有项。
  	// 生成的第一项是索引0处的项,然后是索引1处的项,依此类推。 		
    public Enumeration<E> elements() {
    	// 使用匿名内部类实现Enumeration
        return new Enumeration<E>() {
            int count = 0;
			// 下一个是否还有元素
            public boolean hasMoreElements() {
                return count < elementCount;
            }
			// 返回该元素,并且count+1
            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

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

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

  	/** 
  	* 第index项开始,返回元素o在向量中第一次出现的角标
  	*
  	* @param o 要搜索的元素
  	* @param index 搜索开始的索引
  	*/
    public synchronized int indexOf(Object o, int index) {
        if (o == null) { // 若没有这步操作,将会报错 
        				 // Exception in thread "main" java.lang.NullPointerException	
            for (int i = index ; i < elementCount ; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index ; i < elementCount ; i++)		
                // 注意重写equals()方法 					
                if (o.equals(elementData[i])) 
                    return i;
        }
        // 未找到元素,则返回-1
        return -1;
    }

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

  	// 从 index 处逆向搜索,返回此向量中最后一次出现的指定元素的索引
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

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

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

        return elementData(index);
    }

    // 返回向量的第一个元素(位于索引0)
    public synchronized E firstElement() {
    	// 元素个数为0(即没有为空),则抛出异常 : 枚举中没有更多的元素
        if (elementCount == 0) { 
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

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

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

    // 删除指定索引处的值
    public synchronized void removeElementAt(int index) {
        modCount++;
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        // j : 索引处之后元素的个数 
        int j = elementCount - index - 1;
        // 如果要删除的索引之后有值那么就把之后的值全部向前移一位
        if (j > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, j);
        }
        // 元素数量减1
        elementCount--;
        // 将删除的元素调整到向量末尾后设置为null
        elementData[elementCount] = null; /* to let gc do its work */
    }

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

  	// 在向量末尾添加元素obj		
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        // 先将末尾设置为obj后,元素个数加1(很巧妙)
        elementData[elementCount++] = obj;
    }

   	// 从此向量中移除变量的第一个(索引最小的)匹配项
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

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

        elementCount = 0;
    }

  	// 重写了父类clone()方法
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
            // 重新new一个对象,从而不影响原向量
            Vector<E> v = (Vector<E>) super.clone();
            v.elementData = Arrays.copyOf(elementData, elementCount);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) { 
        	// 如果对象的类不支持 Cloneable 接口,则重写 clone 方法的子类也会抛出此异常,
        	// 以指示无法复制某个实例
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

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

 	@SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
    	// 当创建的数组的长度小于向量集的大小,则直接通过Arrays方法进行复制
        // 但这样会新建一个数组T[]
        if (a.length < elementCount) 					
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());	
		// 创建的数组长度大于向量集的大小
        System.arraycopy(elementData, 0, a, 0, elementCount); // 先将向量集中的元素复制到创建的数组中
		// 大于向量集的元素将赋值为null
        if (a.length > elementCount) 
            a[elementCount] = null;
		// 若创建的数组的大小刚好和向量集大小相同,则直接返回复制好的数组a.
        return a; 
    }
   
 
    // 辅助方法
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

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

        return elementData(index);
    }

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

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

 	// 移除此向量中指定元素的第一个匹配项
    public boolean remove(Object o) {
        return removeElement(o);
    }

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

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

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

        return oldValue;
    }

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

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

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

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

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

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

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

        int numMoved = elementCount - index;
        // 将索引之后的元素向右移动(索引+集合的个数)位(即空出位置来让集合的元素插入)
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
		// 复制集合中的元素到向量已经留好的位置
        System.arraycopy(a, 0, elementData, index, numNew);
        elementCount += numNew;
        return numNew != 0;
    }

    // 当且仅当指定的对象也是一个 List、两个 List 大小相同,
    // 并且其中所有对应的元素对都相等 时才返回 true
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }

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

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

   	// 返回此 List 的部分视图,元素范围为从 fromIndex(包括)到 toIndex(不包括).
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
                                            this);
    }

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

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

  	// 从流(即反序列化)加载代码向量实例。此方法执行检查以确保字段的一致性
    private void readObject(ObjectInputStream in)
            throws IOException, ClassNotFoundException {
        ObjectInputStream.GetField gfields = in.readFields();
        int count = gfields.get("elementCount", 0);
        Object[] data = (Object[])gfields.get("elementData", null);
        if (count < 0 || data == null || count > data.length) {
            throw new StreamCorruptedException("Inconsistent vector internals");
        }
        elementCount = count;
        elementData = data.clone();
    }

   	// 将代码向量实例的状态保存到流(即序列化它)。此方法执行同步以确保序列化数据的一致性。
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        final java.io.ObjectOutputStream.PutField fields = s.putFields();
        final Object[] data;
        synchronized (this) {
            fields.put("capacityIncrement", capacityIncrement);
            fields.put("elementCount", elementCount);
            data = elementData.clone();
        }
        fields.put("elementData", data);
        s.writeFields();
    }

    // 从列表中的指定位置开始,返回列表中的元素(按正确顺序)的列表迭代器。
    public synchronized ListIterator<E> listIterator(int index) {
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

  	// 返回列表中的列表迭代器(按适当的顺序)。
    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

   	// 以正确的顺序返回该列表中的元素的迭代器。
    public synchronized Iterator<E> iterator() {
        return new Itr();
    }

Vector类中的Itr私有类实现Iterator接口

	// 继承Iterator
    private class Itr implements Iterator<E> {
    	// 光标指向元素的前面,初始光标指向向量第一个元素的前面.
		// 举例 : ^ 1 2 3 4 5 (每次向后移动,光标的值都会加一)
		// 向后移:1 ^ 2 3 4 5
		// ...
		// 移到最后:1 2 3 4 5 ^
		// 当移动到最后时,此时光标的值为5,与向量的实际大小相等
        int cursor;       // index of next element to return
        // 每当光标移动后,lastRet的值都等于光标移动前的值.初始为-1
        int lastRet = -1; // index of last element returned; -1 if no such
        // 期望修改的次数初始与修改的次数相等
        int expectedModCount = modCount;

		// 判断光标后面是否还有值
        public boolean hasNext() {
            // Racy but within spec, since modifications are checked
            // within or after synchronization in next/previous
            // 若光标已经移到了最后,光标大小为5,与元素的实际大小相等,返回false,证明元素之后没值的标准
            return cursor != elementCount;
        }

		// 取出光标后的值,并将光标后移一位
        public E next() {
            synchronized (Vector.this) {
            	// 先检测向量是否被修改过
                checkForComodification();
                int i = cursor;
                // 判断光标之后是否有值
                if (i >= elementCount)
                    throw new NoSuchElementException();
                // 光标后移一位
                cursor = i + 1;
                // 取出光标移动之前所在的值
                // ^ 1 2 3 4 5
                // 光标在第一个元素之前的话,光标的值为0,那么取出的值也就是elementData[0],
                // 然后光标的值加1(也就是所谓的后移一位. 1 ^ 2 3 4 5)
                // 在此调用next()方法时,光标已经加1,那么取出的值也就是elementData[1],
                // 光标继续后移一位(也就是指向第二个元素的后面, 1 2 ^ 3 4 5)
                return elementData(lastRet = i);
            }
        }

		// Iterator类中自带的remove()方法
        public void remove() {
        	// 先判断光标是否移动过,光标移动后,将光标移动前的值赋值给lastRet
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                // 借助Vector的remove方法,此时modCount的值会加1
                Vector.this.remove(lastRet); // 将移除光标前的元素
                // Iterator不允许其他类的增删操作,只允许自己,                
                // 删除元素之后把修改过的次数重新赋值预期修改的次数
                expectedModCount = modCount;
                // 这样也就好理解了.自己类的增删操作,是可以预期的,
                // 而迭代类之外的操作光标的位置啥的都乱了,难以维护,可能也是为了避免繁琐的逻辑,直接不允许其他类在迭代的时候进行操作
            }
            // 删除元素之后,重新维护光标的位置,此时光标向前移1位
            // 举例 : 1 2 3 ^ 4 5 (此时执行remove()方法)
            // 删后 : 1 2   ^ 4 5 (此时4个元素,光标的值位3,但光标很明显在第二值的后面嘛
            // 因此,光标向前移一位
            cursor = lastRet;
            // 最后一个元素被删除,返回的最后一个元素没值,因此重置lastRet的值为-1
            lastRet = -1;
            // 也正是因为被重置为-1,因此不允许连续进行remove方法,需要移动之后才可以继续执行remove方法.
        }

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

        final void checkForComodification() {
        	// 判断是否进行过迭代的方法之外的增删操作
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * An optimized version of AbstractList.ListItr
     */
     // 该类与Iterator相比,增加了向前遍历的方法,而且增加了修改与增加元素,
     // 且该类继承了Iterator类,因此上面的方法该类也是同样适用的
    final class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

		// 判断前面是否还有元素
        public boolean hasPrevious() {
            return cursor != 0;
        }

		// 返回光标的位置(下一个元素的索引)
        public int nextIndex() {
            return cursor;
        }

		// 前一个值的索引(光标的位置减一) 
        public int previousIndex() {
            return cursor - 1;
        }

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

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

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

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

    @Override
    @SuppressWarnings("unchecked")
    public synchronized boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final int size = elementCount;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            elementCount = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

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

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

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

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

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

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

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

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

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

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

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
}


  1. 作者:欧阳思海
    链接:https://juejin.im/post/5afc329cf265da0b7026187a ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值