ArrayList源码...纯属自嗨

纯属自嗨,,,肯定有错。

参考文章:

Spliterator:https://blog.csdn.net/lh513828570/article/details/56673804

BitSet:https://blog.csdn.net/jiangnan2014/article/details/53735429

UnaryOperator:https://blog.csdn.net/qq_28410283/article/details/80634319

没有涉及的部分:接口和包的继承层次、排序算法、BitSet实现

package java.util;

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

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
	
    private static final long serialVersionUID = 8683452581122892189L;/*序列化ID*/
    
    private static final int DEFAULT_CAPACITY = 10;/*默认容量,并不是用在初始化*/
    
    private static final Object[] EMPTY_ELEMENTDATA = {};/*空表共享数组,节省空间*/
    
    /*用这个和默认的区分开,便于知道第一次添加元素需要增加的容量*/
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
    /*存储元素,ArrayList容量等于数组长度。
    对于空构造创建的ArrayList,elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA
		第一次添加元素将对elementData扩容到10*/
    transient Object[] elementData; // non-private to simplify nested class access
    /*方法writeObject可以用于解释为什么elementData要使用transient修饰:*/
    /*
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;//存储修改次数
        s.defaultWriteObject();//存储非static和transient信息

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);//存储size

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {//存储size大小的数组,而不是elementData.length大小的数组
        	//节省空间
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
    */
		
		/*ArrayList中存储的元素
    必要的,如果没有。添加一个null和空ArrayList将无法区分。
    好吧,你们喜闻乐见的性能也是一个因素。
    但是相对于没有size就会产生严重的逻辑错误而言,性能反而不重要*/
    private int size;
   
    /*指定容量的构造
    指定容量为0--使用EMPTY_ELEMENTDATA构造
    指定容量为负数--抛出异常*/
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /*无参构造,采用DEFAULTCAPACITY_EMPTY_ELEMENTDATA*/
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /*使用一个已有集合进行构造,优先调用集合的toArray方法
    如果集合非空,确保赋Object[]类型的数组给elementData
    如果集合为空,用EMPTY_ELEMENTDATA构造*/
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /*缩小容量,将modCount值+1,确保Iterator操作不会出现错误*/
    /*Arrays.copyOf方法调用:
    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }
    上一个方法调用:
    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
    说白了,就是在elementData长度和size中间选取一个比较小的
    同时elementData的类型还是动态编译的
    知道用Arrays.copyOf方法扩容,实际上还是用了System.arrayCopy方法
    System.arrayCopy方法在复制一个数组的时候,会建立一个临时的数组,这点需要注意一下*/
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    
    /*如果是无参构造,取0;一参构造取10。若传参大于0或10,扩容
    注意:方法可见性是public,用户可以调用*/
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

		/*将容量最小扩充到10(骗你的,不是最小是10哈哈哈)
		如果是无参构造,最小扩充10
		如果指定参数,或者已经经过操作,根据传参扩充容量*/
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

		/*直译:确保显式容量
		在其中对于elementData进行了操作,因此modCount+1
		看起来像是minCapacity > elementData.length的话,就调用增长容量的方法*/
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /*
    	The maximum size of array to allocate.
      Some VMs reserve some header words in an array.
      Attempts to allocate larger arrays may result in
      OutOfMemoryError: Requested array size exceeds VM limit
      意思是:一些虚拟机会存储一些头信息,若尝试申请更大的数组,可能导致内存超限
    */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /*
    	扩充容量,确保minCapacity数量的数组能被存储
    	如果传参大于elementData.length * 1.5,让newCapacity = minCapacity
    	如果之后newCapacity大于Integer.MAX_VALUE-8调用方法hugeCapacity
    */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

		/*
			hugeCapacity(int)方法调用基于newCapacity - MAX_ARRAY_SIZE > 0
			负值 - 负值可能会产生溢出
			所以上述条件可以转化为:newCapacity - MAX_ARRAY_SIZE < Integer.MIN_VALUE
			即newCapacity - Integer.MAX_VALUE + 8 < Integer.MIN_VALUE
			即newCapacity < -9
			即,若hugeCapacity(int)方法调用,传参一定小于-9,这是底线。
			而grow(int)方法中的newCapacity可以是elementData.length + elementData.length >> 1
			也可以是用户从ensureCapacity(int)传来的参数
			而在ensureCapacity(int)方法中确保了minCapacity > minExpand(0 or 10)
			故不存在第二种情况
			只有可能是elementData.length + elementData.length >> 1越界
			这个条件并不难达到。
			故有此检查
			拙见。。。不一定正确
		*/
    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 int size() {
        return size;
    }

    /*同上*/
    public boolean isEmpty() {
        return size == 0;
    }

    /*也是数据结构书上都会提到的实现方法*/
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

   	/*判断很有意思,有很多种可以替代的写法,但是这种写法不仅可以避免空指针
   	且耗时少
   	这都是自己写代码可以借鉴的*/
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /*基本方法同上*/
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /*
    	此时可以简单介绍一下Cloneable接口的作用
    	Cloneable接口没有定义任何方法,clone方法是定义在Object类中的protected方法
    	对于非子类是不可见的。
    	clone方法相当于创建一个新的对象,并将对象中的引用赋给新对象(看例子)
    	public class ArrayList1Test {
    		public static void main(String[] args) {
       		A a1 = new A();
        	A a2 = (A) a1.clone();
        	a1.b.name = "ccccc";
        	System.out.println(a2.b.name);
    		}
			}
			class A implements Cloneable {
    		B b = new B();
    		public Object clone() {
        	try {
            return super.clone();
        	} catch (CloneNotSupportedException e) {
            e.printStackTrace();
        	}
        	return null;
    		}
			}
			class B {
    		String name;
			}
			结果是ccccc
			注意:我们在实现clone方法的时候,除了要将clone方法的可见性扩大到public范围
			而且要将实现clone方法的类中所有的成员变量调用clone方法全部赋值
			确保克隆的深度
    */
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    /*提供基于Arraylist新创建的array,容量是size*/
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /*如果a容量小,容量扩充为size(返回一个新的数组)
    如果a容量大,返回原先的数组,并将a[size] = null(不知何意)*/
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // Positional Access Operations
		/*emm就是get(int)方法的简化版*/
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /*将对于参数的检查作为一个private方法,我们可以借鉴*/
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

    /*不解释*/
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /*在进行添加扩容(说扩容检查之前更加合适)时已经将modCount + 1
    之后就是最后一个值赋值*/
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    /*需要注意,arrayCopy方法将会创建一个临时数组用于复制*/
    public void add(int index, E element) {
        rangeCheckForAdd(index);//检查

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

    /*需要注意的在方法中*/
    public E remove(int index) {
        rangeCheck(index);//检查

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0) //一般而言size - 1 > index是确定的,除了尾删除
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
                             //从index + 1到末尾的长度是(size - 1) - (index + 1) + 1
        //尾删除和一般情况的完美重合
        elementData[--size] = null; // clear to let GC do its work(垃圾回收)

        return oldValue;
    }

    /*if的写法和indexOf等方法差不多*/
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    /*就是,,,没有index检查了*/
    private void fastRemove(int index) {
        modCount++;//不能少
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

    /*不解释*/
    public void clear() {
        modCount++;

        // clear to let GC do its work(垃圾回收)
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    /*不解释*/
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    /*从index开始添加所有的Collection中的元素*/
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;/*(size - 1) - (index) + 1*/
        if (numMoved > 0) //若 非尾插,移动元素
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
                             /*因为插入后,插入的最后一个值的下标是index + numNew - 1*/

        System.arraycopy(a, 0, elementData, index, numNew);/*插入*/
        size += numNew;
        return numNew != 0;
    }

    
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;//(size - 1) - (toIndex) + 1
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
                         /*将toIndex ~ size - 1的元素前移*/

        // clear to let GC do its work(垃圾回收)
        //正好,剩余元素的个数 = 多余元素的第一个下标值
        int newSize = size - (toIndex-fromIndex);/*总个数 - (移出个数 + 1)*/
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    /*参数检验方法*/
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /*参数检验*/
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /*辅助方法*/
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /*集合运算,差集*/
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);//判空
        return batchRemove(c, false);
    }

    /*集合运算,交集*/
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);//判空
        return batchRemove(c, true);
    }

		/*根据给出的complement变量来求差集或者并集
		true是求交集
		false是求差集*/
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;/*备份*/
        int r = 0, w = 0;
        /*R:将要判断元素的下标;W:符合条件的元素将要入集合的下标*/
        boolean modified = false;//标记
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {//出现异常和上述流程执行完毕都共用以下流程
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {//如果抛出异常(try中),剩下的元素
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);//将后面的元素作为符合条件的元素
                w += size - r;//w加上刚刚复制的元素
            }
            if (w != size) {//有元素符合要求
                // clear to let GC do its work(垃圾回收)
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;//更改的次数
                size = w;//缩小数组容量
                modified = true;//标记变化(有元素符合要求)
            }
        }
        return modified;
    }

    /*可以用于解释为什么elementData是用transient修饰的*/
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;//存储修改次数
        s.defaultWriteObject();//存储非static和transient信息

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);//存储size

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {//存储size大小的数组,而不是elementData.length大小的数组
        	//节省空间
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /*读出对象*/
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;
				//读出的顺序和写入的顺序一样?
        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in capacity
        s.readInt(); // ignored

        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

    /*本宝宝没有经常使用过,经常不使用Iterator及其衍生接口*/
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)//参数检查
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);//根据传入的index创建一个新对象
    }

    /*基本同上*/
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

   	/*大名鼎鼎的iterator方法*/
    public Iterator<E> iterator() {
        return new Itr();
    }

    /*在ArrayList内部的Iterator实现类
    真让人想象是不是所有的Iterator都是这样实现的*/
    private class Itr implements Iterator<E> {
        int cursor;/*将要返回的下标*/
        int lastRet = -1;/*刚刚返回的list下标*/
        int expectedModCount = modCount;/*期望的modCount变量*/

				/*判断是否有下一个*/
        public boolean hasNext() {
            return cursor != size;
        }

				/*获得下一个元素*/
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();//如果有多线程问题
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();//如果超过下限
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
                //双重检查(可能害怕之后又有线程将elementData改变?)
            cursor = i + 1;//下标加一
            return (E) elementData[lastRet = i];//返回
        }

				/*移除lastRet对应元素*/
        public void remove() {
            if (lastRet < 0)//即lastRet = -1
                throw new IllegalStateException();
            checkForComodification();//多线程检查

            try {
                ArrayList.this.remove(lastRet);//调用移除方法(外部类)
                cursor = lastRet;//cursor = cursor - 1
                lastRet = -1;//上一个返回的元素已经从ArrayList中清除,不存在上一个返回的下标
                expectedModCount = modCount;//因为remove方法修改了modCount
            } catch (IndexOutOfBoundsException ex) {
            	//访问过程中可能其他线程修改本ArrayList,使elementData产生变化
                throw new ConcurrentModificationException();
            }
        }

				/*在每一个方法上都执行由Consumer提供的操作*/
				/*关于Consumer:参考我写的另外一个文章*/
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);//判空
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {//如果将要返回的元素不存在
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
            	//如果过程汇中有线程修改elementData长度(不完全覆盖的检查)
            	//实际上就是尽最大可能保证线程的安全
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
            	//每一次都进行多线程安全的检查
                consumer.accept((E) elementData[i++]);//执行操作
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;//一般情况下,cursor将会为size
            lastRet = i - 1;//lastRet将会等于size- 1
            //如果提前结束(多线程引起的modCount != expectedModCount)
            checkForComodification();//在此处抛出异常
        }

				/*检查方法
				如果其他线程对于elementData进行了任何改变(导致modCount发生变化)
				抛出异常*/
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /*根据List构造的独有的Iterator*/
    private 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;
        }

				/*获得前驱节点*/
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();//线程安全
            int i = cursor - 1;//将要返回节点的前驱节点下标
            if (i < 0)
                throw new NoSuchElementException();//越界
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
            //如果其他线程使条件成立
                throw new ConcurrentModificationException();
            cursor = i;//更新cursor的值
            return (E) elementData[lastRet = i];//刚刚返回的值赋值
            //有意思的是,此时cursor和lastRet的值相等
        }

				/*赋值*/
        public void set(E e) {
            if (lastRet < 0)//越界
                throw new IllegalStateException();
            checkForComodification();//多线程检查

            try {
                ArrayList.this.set(lastRet, e);//调用外部类
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        
        /*添加*/
        public void add(E e) {
            checkForComodification();//多线程检查

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;//更新下标
                lastRet = -1;
                expectedModCount = modCount;//修改了elementData
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /*返回一个范围内的,代表ArrayList中真实元素的子集
    允许通过子集实现对父集的批量(或单独)操作*/
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

		/*都是基础的判断*/
    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    }

		/*子集,应该叫子表更加合适*/
    private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;//父表引用
        private final int parentOffset;
        //子表下标 + parentOffset = 父表下标,提供给parent父表使用
        private final int offset;
        //offset + index永远表示相对于整个表的下标,提供给整个ArrayList使用
        int size;//记录子表大小

        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            this.parent = parent;
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = ArrayList.this.modCount;
        }

        public E set(int index, E e) {
            rangeCheck(index);//下标检查
            checkForComodification();//线程安全检查
            E oldValue = ArrayList.this.elementData(offset + index);
            //之前的值,利用offset + index找到父表的对应元素
            ArrayList.this.elementData[offset + index] = e;//替代
            return oldValue;
        }

        public E get(int index) {
            rangeCheck(index);//下标检查
            checkForComodification();//线程安全
            return ArrayList.this.elementData(offset + index);
        }

        public int size() {
            checkForComodification();//线程安全
            return this.size;//返回的当然是子表的大小
        }

        public void add(int index, E e) {
            rangeCheckForAdd(index);//下标检查
            checkForComodification();//线程安全(相对的)
            parent.add(parentOffset + index, e);//parentOffset起了作用
            this.modCount = parent.modCount;//增加会使modCount改变
            this.size++;//本列表的size增加
        }

        public E remove(int index) {
            rangeCheck(index);//下标检查
            checkForComodification();//多线程检查
            E result = parent.remove(parentOffset + index);//移除
            this.modCount = parent.modCount;//modCount改变
            this.size--;//本列表的size减少
            return result;
        }

				/*不解释(基本上全部都是采用 检查 + 操作 + 修改逻辑值 + 返回)*/
        protected void removeRange(int fromIndex, int toIndex) {
            checkForComodification();//线程安全
            parent.removeRange(parentOffset + fromIndex,
                               parentOffset + toIndex);
            this.modCount = parent.modCount;
            this.size -= toIndex - fromIndex;
        }

        public boolean addAll(Collection<? extends E> c) {
            return addAll(this.size, c);
        }

        public boolean addAll(int index, Collection<? extends E> c) {
            rangeCheckForAdd(index);
            int cSize = c.size();
            if (cSize==0)
                return false;

            checkForComodification();
            parent.addAll(parentOffset + index, c);
            this.modCount = parent.modCount;
            this.size += cSize;
            return true;
        }

        public Iterator<E> iterator() {
            return listIterator();//直接返回的是ListIterator而不是Iterator
        }

        public ListIterator<E> listIterator(final int index) {
            checkForComodification();
            rangeCheckForAdd(index);
            final int offset = this.offset;

            return new ListIterator<E>() {
            	//匿名类也是萌萌哒,可以说是对于ListIterator的另一种实现
            	//除了这个方法之外没有方法创建这个实例,用了匿名类
                int cursor = index;
                int lastRet = -1;
                int expectedModCount = ArrayList.this.modCount;

                public boolean hasNext() {
                    return cursor != SubList.this.size;
                }

                @SuppressWarnings("unchecked")
                public E next() {
                    checkForComodification();
                    int i = cursor;
                    if (i >= SubList.this.size)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i + 1;
                    return (E) elementData[offset + (lastRet = i)];
                }

                public boolean hasPrevious() {
                    return cursor != 0;
                }

                @SuppressWarnings("unchecked")
                public E previous() {
                    checkForComodification();
                    int i = cursor - 1;
                    if (i < 0)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i;
                    return (E) elementData[offset + (lastRet = i)];
                }

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

                public int nextIndex() {
                    return cursor;
                }

                public int previousIndex() {
                    return cursor - 1;
                }

                public void remove() {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        SubList.this.remove(lastRet);
                        cursor = lastRet;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void set(E e) {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        ArrayList.this.set(offset + lastRet, e);
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void add(E e) {
                    checkForComodification();

                    try {
                        int i = cursor;
                        SubList.this.add(i, e);
                        cursor = i + 1;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                final void checkForComodification() {
                    if (expectedModCount != ArrayList.this.modCount)
                        throw new ConcurrentModificationException();
                }
            };
        }

				/*从子表中再次分出一个子表*/			
        public List<E> subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new SubList(this, offset, fromIndex, toIndex);
            //这里的offset传参就是offset
            //因为初始化参数中offset = offset + fromIndex(传入的offset + 初始位置)
            //对于整个表的补偿
        }

				/*之后的四个方法都是和参数判断和报错相关的方法,ArrayList中都已经见识过了*/
        private void rangeCheck(int index) {
            if (index < 0 || index >= this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private void rangeCheckForAdd(int index) {
            if (index < 0 || index > this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private String outOfBoundsMsg(int index) {
            return "Index: "+index+", Size: "+this.size;
        }

        private void checkForComodification() {
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
        }
				
				/*这个之后我们会见识到的*/
        public Spliterator<E> spliterator() {
            checkForComodification();
            return new ArrayListSpliterator<E>(ArrayList.this, offset,
                                               offset + this.size, this.modCount);
        }
    }

		/*不解释,这可是ArrayList的forEach*/
    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /*看后面*/
    @Override
    public Spliterator<E> spliterator() {
        return new ArrayListSpliterator<>(this, 0, -1, 0);
    }

    /*splitable iterator可分割迭代器,不允许对ArrayList进行任何结构上的操作*/
    /*参考:https://blog.csdn.net/lh513828570/article/details/56673804*/
    static final class ArrayListSpliterator<E> implements Spliterator<E> {
        private final ArrayList<E> list;//代表的list对象
        private int index; //当前位置
        private int fence; //能访问到最后一个元素的下一个(初始值是-1)
        private int expectedModCount; //在fence初始化时初始化

				/*给定list,起始位置,结束位置和修改次数创建新的ArrayList的Spliterator对象*/
        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                             int expectedModCount) {
            this.list = list; // OK if null unless traversed
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

				/*方法可见性private
				为fence、expectedModCount初始化*/
        private int getFence() { // initialize fence to size on first use
            int hi; // (a specialized variant appears in method forEach)
            ArrayList<E> lst;
            if ((hi = fence) < 0) {//fence没有初始化
                if ((lst = list) == null)//空检验
                    hi = fence = 0;
                else {//非空
                    expectedModCount = lst.modCount;//expectedModCount初始化
                    hi = fence = lst.size;//fence初始化
                }
            }
            return hi;
        }

        public ArrayListSpliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;//无符号右移
            //求得当前位置和上界的一半
            return (lo >= mid) ? null : // divide range in half unless too small
                new ArrayListSpliterator<E>(list, lo, index = mid,
                                            expectedModCount);
                                            //按照容量进行的分割,容量太小不予分割
                                            //分割的新Spliterator以index为起始位置
                                            //以mid为终止位置
                                            //同时原来的Spliterator将从mid开始
        }

				/*尝试对下一个元素进行操作*/
        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            if (i < hi) {
                index = i + 1;//下一个元素
                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

				/*对所有元素*/
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi, mc; // hoist accesses and checks from loop
            ArrayList<E> lst; Object[] a;
            if (action == null)//判空
                throw new NullPointerException();
            if ((lst = list) != null && (a = lst.elementData) != null) {
                if ((hi = fence) < 0) {//没有初始化
                    mc = lst.modCount;
                    hi = lst.size;
                }
                else
                    mc = expectedModCount;//初始化之后
                if ((i = index) >= 0 && (index = hi) <= a.length) {
                    for (; i < hi; ++i) {
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (lst.modCount == mc)//如果中间没有线程修改这个list
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

				/*estimate 估算
				估算没有处理的个数*/
        public long estimateSize() {
            return (long) (getFence() - index);
        }

				/*布吉岛啊啊啊啊,听说是返回特征值*/				
        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

		/*如果符合Predicate的判断,移除(批量)*/
    @Override
    /*关于其中出现的BitSet,只需要有个最简单的认知即可
    即:利用每一位来标识连续的元素是否在某一个数据结构中出现*/
    /*BitSet参考:https://blog.csdn.net/jiangnan2014/article/details/53735429*/
    public boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);//判空
        int removeCount = 0;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);//将i标记下来(应该是第i位变成true),默认false
                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;//移除之后的size
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
            	/*Returns the index of the first bit that is set to false that occurs on or after the specified starting index.*/
            	/*返回基于或等于i的下一个false值的下标*/
                i = removeSet.nextClearBit(i);
                /*将没有remove的元素从0开始赋值*/
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {//将剩余元素置空(垃圾回收)
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

		/*关于UnaryOperator的使用:
		public class Main {
    	public static void main(String[] args) throws Exception {
        A a0 = new A();
        UnaryOperator<A> unaryOperator = a -> {a.name = "cc";return a;};
        System.out.println(unaryOperator.apply(a0).name);
    	}
		}

		class A{String name;}
		详情:https://blog.csdn.net/qq_28410283/article/details/80634319*/
    @Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);//判空
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

		/*排序,,,最好先不要纠结怎么实现的*/
    @Override
    @SuppressWarnings("unchecked")
    public void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }
}

猜你喜欢

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