Vector 源码-自嗨

package java.util;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    //用于存储元素
    protected Object[] elementData;

    //其实就是size
    protected int elementCount;

    //看名字就是增长量,如果非正,每次容量变为原先的两倍
    protected int capacityIncrement;

    //序列化id
    private static final long serialVersionUID = -2767605614048989439L;

    //初始化啊~
	//给出增长量和初始容量
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

    //依旧是初始化,从0可以看出,默认两倍增长
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    //无参构造,默认容量10,增长以二倍形式
    public Vector() {
        this(10);
    }

    //给定值的初始化
    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) //可能是T[],而不是Object[]
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

    //将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 ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

    //尝试扩容(如果要求容量大于数组长度的话就扩容)
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
			//也是负数 - 正数,有可能大于0(如果不是通过ensureCapacity方法调用的话,需要额外注意)
		//和ArrayList一个样
            grow(minCapacity);
    }

    //同ArrayList,ArrayList中也是一样的值
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    private void grow(int minCapacity) {
        //旧容量
        int oldCapacity = elementData.length;
		//由此可见,如果capacityIncreament小于或者等于0,扩容之后的容量是原先的两倍
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
		//newCapacity存在溢出的问题吗?存在!(溢出之后直接是负值)
		//minCapacity可能是负值吗?如果方法从ensureCapacityHelper调用,可能!
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
			//第一种情况:newCapacity是负值,溢出(上面的注释中解释过newCapacity可以是负值)
			//第二种情况:newCapacity非常大
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
		//这里还是喜闻乐见的对于溢出的处理
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;//这个是处理我上面说的第二种情况
    }

    //
    public synchronized void setSize(int newSize) {
        modCount++;//结构化修改
        if (newSize > elementCount) {//如果传参大于当前元素个数
            ensureCapacityHelper(newSize);//尝试扩容
        } else {
            for (int i = newSize ; i < elementCount ; i++) {//将newSize后面的删除
                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;
    }

    //toEnumeration方法(笑~)
    public Enumeration<E> elements() {
        return new Enumeration<E>() {//谁让返回的是一个匿名内部类呢~
            int count = 0;

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

            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
						//说句非常不敬的话:
						//我真的觉得这个elementData方法写的宛如一个智障
						//算了,我不行,我不上,我不逼逼(笑~)
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

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

    //查询
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    //基于index查询,返回index(含)之后第一次出现o的下标位置
    public synchronized int indexOf(Object o, int index) {
        if (o == null) {//看来vector也是可以允许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;
    }

    //最晚出现o的下标
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount-1);
    }

    //从后向前查
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)//参数检查
            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

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

    //get方法
    public synchronized E elementAt(int index) {
        if (index >= elementCount) {//下标检查
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }

        return elementData(index);//这不是之前的蠢方法吗?
    }

    //返回第一个
    public synchronized E firstElement() {
        if (elementCount == 0) {//表状态的检查
            throw new NoSuchElementException();
        }
        return elementData(0);//你懂
    }

    //挺无聊的方法
    public synchronized E lastElement() {
        if (elementCount == 0) {//表的状态
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);//返回最后一个元素
    }

    //和set方法基本相同
	//除了参数顺序和返回值
    public synchronized void setElementAt(E obj, int index) {
        if (index >= elementCount) {//下标检查
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        elementData[index] = obj;//如果小于0报错
    }

    //和remove方法相同
    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);
			//从index + 1开始到最后,复制到idnex开始的elementCount - index - 1个
        }
        elementCount--;
        elementData[elementCount] = null; //gc
    }

    //指定位置插入
    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);
		//从index开始的elementCount - index个复制到index + 1之后
        elementData[index] = obj;//插入
        elementCount++;//size ++
    }

    //尾插
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);//尝试扩容
        elementData[elementCount++] = obj;//插入
    }

    //值删
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    //clear
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

    //克隆方法
	//除了modCount变成0之外...
	//数组是复制的
    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);
        }
    }

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

    @SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
        if (a.length < elementCount)//容量不匹配的情况,取用a的类型和Vector的大小
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
		
		//容量匹配
        System.arraycopy(elementData, 0, a, 0, elementCount);

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

        return a;
    }

    // Positional Access Operations

    @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;
    }

    //你在用英文的时候能用Component吗?(笑~)
    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();
    }

    // Bulk Operations

    //调用的是AbstractCollection中的containAll方法,就是一个循环,然后判断罢了
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }
	/*
	public boolean containsAll(Collection<?> c) {//AbstractCollection的方法
        for (Object e : c)//遍历c
            if (!contains(e))//是否存在?
                return false;//不存在直接false
        return true;//都存在true
    }
	*/

    //添加所有
    public synchronized boolean addAll(Collection<? extends E> c) {
        modCount++;//结构修改
        Object[] a = c.toArray();//toArray方法
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);//尝试扩容
        System.arraycopy(a, 0, elementData, elementCount, numNew);//不解释(插入)
        elementCount += numNew;//元素个数增加
        return numNew != 0;//如果numNew == 0,说明一个元素也没有添加进去
    }

    //移除所有
	//调用的是AbstractCollection中的removeAll方法
    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())) {//c中是否有这个元素
                it.remove();//有的话删除(利用迭代器)
                modified = true;//进行了删除操作
            }
        }
        return modified;
    }
	*/

    //保留c中的元素
	//调用了AbstractCollection中的retainAll方法
    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;
    }
	*/

    //从指定位置开始添加所有
    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;
		//因为从1~2是两个,所以从index~elementCount-1是elementCount-1-index+1=elementCount-index个
        if (numMoved > 0)//如果移动的个数大于0(也就是index < elementCount,即非尾插)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
		//将index开始到elementCount-1的数据复制到从index+a.length到a.length+elementCount-1的位置上

		//将a从0开始到a.length-1位置上的数据复制到elementData从idnex开始到index+a.length-1的位置上
        System.arraycopy(a, 0, elementData, index, numNew);
        elementCount += numNew;//修改个数
        return numNew != 0;//如果修改个数不为0
    }

    //调用AbstractList方法
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }
	/*
	public boolean equals(Object o) {
        if (o == this)//o是他本身
            return true;//返回true
        if (!(o instanceof List))//如果o不是一个List
            return false;//直接返回false

			//获得两个iterator(还是ListIterator)
        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;//返回false
        }
        return !(e1.hasNext() || e2.hasNext());//就算之前都相等,还要看看两个list的大小是否相同
		//不先比大小的原因可能是因为链表吧,但是这样比真的比先比大小的方法更好
    }
	*/

    //调用了AbstractList的同名方法
    public synchronized int hashCode() {
        return super.hashCode();
    }
	/*
	public int hashCode() {
        int hashCode = 1;//初始值
        for (E e : this)//遍历
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());//同每一个元素的位置和大小都有关系
        return hashCode;
    }
	*/

    //调用了AbstractCollection的同名方法
    public synchronized String toString() {
        return super.toString();
    }
	/*
	public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())//如果没有元素
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);//哇,还有列表元素引用自身的处理
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }
	*/

    //返回子表
	//其实个人感觉的话和ArrayList里面的差不多
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        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);
		//从elementData的toIndex位置开始复制elementCount - toIndex个到fromIndex位置

		//新的个数
        int newElementCount = elementCount - (toIndex-fromIndex);
        while (elementCount != newElementCount)//当个数还不是新个数的时候
            elementData[--elementCount] = null;//从最后一个向前赋值null
    }

	//这个方法,不做了解
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        final java.io.ObjectOutputStream.PutField fields = s.putFields();
        final Object[] data;
        synchronized (this) {
            fields.put("capacityIncrement", capacityIncrement);
            fields.put("elementCount", elementCount);
            data = elementData.clone();
        }
        fields.put("elementData", data);
        s.writeFields();
    }

    //返回一个ListIterator对象,从指定位置开始
    public synchronized ListIterator<E> listIterator(int index) {
        if (index < 0 || index > elementCount)//参数检验
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);//返回Iterator
    }

    //你懂
    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    //和上面方法不同的是,他返回的是Iterator对象而不是ListIterator对象
    public synchronized Iterator<E> iterator() {
        return new Itr();
    }

    //优化版本
    private class Itr implements Iterator<E> {
        int cursor;       //将要返回的下标
        int lastRet = -1; //刚刚返回的下标
        int expectedModCount = modCount;//期望的修改值

        public boolean hasNext() {
            //将要返回的下标不是大小就行
            return cursor != elementCount;
        }

		//不在方法上加锁是有原因的
		//我们需要的是不能同时对vector进行操作
		//而不是保证不能同时针对迭代器调用next方法
        public E next() {//返回下一个
            synchronized (Vector.this) {
                checkForComodification();//检查修改值
                int i = cursor;
                if (i >= elementCount)//当前值已经大于或者等于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);//移除(modCount已经在remove方法中变动)
                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++]);//执行操作
                }
                // 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) {//Iterator不支持指定开始位置
            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)//同remove等方法
                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;
        }
    }

	//这个是Vector的方法
	//对每一个元素做相同的操作
    @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) {//修改检查
		//(主要针对的是循环中由于modCount != exceptedModCount而跳出的情况)
            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);//ArrayList的同名方法中用过
		//其实可以利用一个ArrayList把移动的下标记住,但是用BitSet省空间
        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);//返回基于i的下一个没有被标记的下标
                elementData[j] = elementData[i];//把没有移动的元素移动到前面
            }
            for (int k=newSize; k < size; k++) {//gc
                elementData[k] = null;  // Let gc do its work
            }
            elementCount = newSize;//元素个数赋值为新的个数
            if (modCount != expectedModCount) {//检查修改情况
                throw new ConcurrentModificationException();
            }
            modCount++;//修改次数+1
        }

        return anyToRemove;//返回是否进行了移动
    }

	//替换所有
	//如果不考虑内存的话,其实和forEach方法差不多。
    @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);
    }

	//并行迭代器
    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; //上限
        private int expectedModCount; // initialized when fence set

        //构造
        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) {//fence没有初始化
                synchronized(list) {
                    array = list.elementData;//初始化array
                    expectedModCount = list.modCount;//初始化exceptedModCount
                    hi = fence = list.elementCount;//初始化边界
                }
            }
			//如果初始化的话,hi=fence
            return hi;//返回上限
        }

        public Spliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;//无符号右移
			//上面的右移应该已经考虑到了溢出的情况
            return (lo >= mid) ? null ://如果index目前的值要大于中间情况
			//说明这个Iterator已经遍历了一半了,我们就不忍心分割了。
                new VectorSpliterator<E>(list, array, lo/*index|origin*/, index = mid,
                                         expectedModCount);
				//将index到中间值的部分分给新的并行迭代器,然后我们从中间(mid)开始遍历
        }

		//向后尝试执行一个元素
        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super E> action) {
            int i;
            if (action == null)//判空
                throw new NullPointerException();
            if (getFence() > (i = index)) {//如果还没有遍历结束
                index = i + 1;//index++
                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) {//这个list不是空
                if ((hi = fence) < 0) {//没有初始化,进行初始化
                    synchronized(lst) {
                        expectedModCount = lst.modCount;
                        a = array = lst.elementData;//取出elementData
                        hi = fence = lst.elementCount;
                    }
                }
                else//已经进行了初始化
                    a = array;//array不为空(因为已经初始化,正常情况理应如此)
                if (a != null && (i = index)/*i=index>=0*/ >= 0 && (index = hi)/*index=fence<=a.length*/ <= 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;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/jdie00/article/details/81908840