Java8源码阅读(1) ---ArrayList

一切尽在代码里,有错误欢迎指出
package org.utils.MyCollection;

import sun.misc.SharedSecrets;

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

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

    private static final long serialVersionUID = 8683452581122892189L;
l
    /**
     * 默认初始化容量
     */
    private static final int DEFAULT_CAPACITY = 0;

    /**
     * 空对象数组
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 默认空对象数组
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * ArrayList元素存储的数组缓冲取
     * ArrayList的大小即这个数组缓冲区的大小,当有元素添加进,原本空的arraylist会被扩展到默认初始化容量
     * transient防止这个数据域序列化
     * 没有设置成private是为了简化嵌套类的操作
     * 由于 ArrayList 是基于动态数组实现的,所以并不是所有的空间都被使用。因此使用了 transient 修饰,可以防止被自动序列化。
     */
    transient Object[] elementData;

    /**
     * 集合元素个数
     */
    private int size;

    /**
     * 数组容量初始化
     * @param initialCapacity
     */
    public MyArrayList(int initialCapacity){
        if(initialCapacity > 0){
            this.elementData = new Object[initialCapacity];
        }else if(initialCapacity == 0){
            this.elementData = EMPTY_ELEMENTDATA;
        }else{
            throw new IllegalArgumentException("非法的数组容量 : " + initialCapacity);
        }
    }

    /**
     * 空构造
     */
    public MyArrayList(){
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 使用外部集合进行构造
     * @param c
     */
    public MyArrayList(Collection<? extends E> c){
        // 持有传入集合的内部数组的引用
        elementData = c.toArray();

        if((size = elementData.length) != 0){
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            // 判断引用的数组类型,并将引用转换成Object数组引用
            if(elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        }else{
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * 用于精简容量
     */
    public void trimToSize(){
        modCount++;
        if(size < elementData.length){
            elementData = (size == 0)
                    ? EMPTY_ELEMENTDATA
                    : Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 确保最小容量 //TODO:有疑问
     * @param minCapacity
     */
    public void ensureCapacity(int minCapacity){
        int minExpend = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                ? 0
                : DEFAULT_CAPACITY; // 不也是0?

        if (minCapacity > minExpend){
            ensureCapacity(minCapacity);
        }
    }

    /**
     * 计算容量,如果传入的为空,则容量返回DEFAULT_CAPACITY和minCapacity之间的较大者
     * @param elementData
     * @param minCapacity
     * @return
     */
    private static int calculateCapacity(Object[] elementData, int minCapacity){
        if(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

    private void ensureCapacityInternal(int minCapacity){
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    /**
     * 确保明确的容量
     * @param minCapacity
     */
    private void ensureExplicitCapacity(int minCapacity){
        modCount++;

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

    /**
     * array容量最大值
     * 减8是因为一些VM在一个array中保留一些头,防止溢出
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 增加容量,确保至少能容纳minCapacity
     * @param minCapacity
     */
    private void grow(int minCapacity){
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 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)
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE)
                ? Integer.MAX_VALUE
                : MAX_ARRAY_SIZE;
    }

    /**
     * 返回list的元素个数
     * @return
     */
    public int size() {
        return size;
    }

    /**
     * 判断是否为空
     * @return
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 判断某个元素是否在list中,底层调用的是indexOf方法
     * @param o
     * @return
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * 返回list中某个元素第一次在list出现的位置,存在返回元素在list中的下标
     * 不存在返回-1
     * @param o
     * @return
     */
    public int indexOf(Object o) {
        // 如果查找的元素为null,则在list中找出第一个null元素
        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;
    }

    /**
     * 从后往前查找元素出现的位置
     * @param o
     * @return
     */
    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;
    }

    /**
     * 浅拷贝
     * @return
     */
    public Object clone() {
        try {
            MyArrayList<?> v = (MyArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }


    /**
     * 返回list的一个Object拷贝实例,相当于创建了一个新的数组实例,元素顺序不变
     * @return
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 泛型方法
     * @param a
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // 返回a的运行时类型,但是内容不变
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        // 调用java本地方法,
        System.arraycopy(elementData, 0, a, 0, size);
        /**
         *  Object src : 原数组
         *  int srcPos : 从元数据的起始位置开始
         *  Object dest : 目标数组
         *  int destPos : 目标数组的开始起始位置
         *  int length  : 要copy的数组的长度
         */
        if (a.length > size)
            a[size] = null;
        return a;
    }

    /**
     * 索引查值
     * @param index
     * @return
     */
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    //*************************** 下面是增删该查方法 ******************************

    /**
     * 查找某个元素
     * @param index
     * @return
     */
    public E get(int index) {
        // index不能大于size
        rangeCheck(index);
        return elementData(index);
    }

    /**
     * 修改某个索引的元素为新元素
     * @param index
     * @param element
     * @return 返回旧元素
     */
    public E set(int index, E element) {
        rangeCheck(index);

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

    /**
     * 增加新元素到list结尾
     * @param e
     * @return
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);
        elementData[size++] = e;
        return true;
    }

    /**
     * 在list某个位置插入元素
     * @param index
     * @param element
     */
    public void add(int index, E element) {
        // 检查index是否合法
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1);
        // 把index后面的位置往后移动一位
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = element;
        size++;
    }

    /**
     * 删除指定位置的元素,返回删除的元素
     * @param index
     * @return
     */
    public E remove(int index) {
        rangeCheck(index);

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

        // 删除元素位置开始到list末尾的元素个数, 即要移动的元素个数
        int numMoved = size - index - 1;
        if (numMoved > 0) {
            // 将index后面的元素向前移动一位
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        }
        // 末尾空出的位置置为null,让垃圾回收器回收
        elementData[--size] = null;

        return oldValue;
    }


    /**
     * 删除list中的所有给定的元素o
     * @param o
     * @return
     */
    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;
    }


    /**
     * 私有方法,不进行边界检查,不返回值,仅删除
     * @param 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;
    }

    /**
     * 清空list, 将所有元素置为null, 垃圾回收器会回收
     */
    public void clear() {
        modCount++;
        for (int i = 0; i < size; i++) {
            elementData[i] = null;
        }
        size = 0;
    }

    /**
     * 将给集合的所有元素添加到list末尾
     * @param c
     * @return
     */
    public boolean addAll(Collection<? extends > c) {
        Object[] a = c.toArray();
        int numNew = a.length;

        ensureCapacityInternal(size + numNew);
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;

    }

    /**
     * 将给定集合中的元素添加到从list的index位置开始到给定集合长度结束
     * 如原来list[1,2,3,4]
     * 给定index=2,c=[11,22]
     * 则返回[1,2,11,22,3,4]
     * @param index
     * @param c
     * @return
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckAdd(index);

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

        int numMoved = size - index;
        if (numMoved > 0)
            // 先腾位置
            System.arraycopy(elementData, index, elementData, index+numNew, numMoved);
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     * 删除指定区间的元素
     * @param fromIndex
     * @param toIndex
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);

        int newSize = size - (toIndex - fromIndex);
        // 垃圾回收
        for (int i = newSize; i < size; i++)
            elementData[i] = null;
        size = newSize;
    }

    /**
     * 范围检查
     * @param index
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 增加元素时范围检查
     * @param index
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 越界异常错误消息
     * @param index
     * @return
     */
    private String outOfBoundsMsg(int index) {
        return "Index: " +index+ ", Size: "+size;
    }

    /**
     * 从list中删除含有指定集合中元素的元素
     * @param c
     * @return
     */
    public boolean removeAll(Collection<?> c) {
        // 判断集合是不是null,如果null,会引发空指针异常
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    /**
     * 从list中删除指定集合以外的元素,保留剩余元素
     * @param c
     * @return
     */
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    /**
     * 批量删除
     * @param c
     * @param complement(是否是补集) 如果为false,移除list中 c集合中的元素
     *                   如果为true,移除list中除了c集合中的所有元素
     * @return 是否删除成功
     */
    private boolean batchRemove(Collection<?> c, boolean complement) {
        // 复制创建一个新的不可变Object数组
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            //遍历数组,并检查这个集合是否对应值,移动要保留的值到数组前面,w最后值为要保留的值得数量
            //如果保留:将相同元素移动到前段,如果不保留:将不同的元素移动到前段
            for (; r < size; r++) // 遍历当前list
                if (c.contains(elementData[r]) == complement) { // 如果当前元素在待删除集合中
                    // w和r两个指针同步往前走的,但一定 w <= r
                    // 待删除的元素的位置被
                    elementData[w++] = elementData[r];
                }
        } finally {
            //最后 r=size 注意for循环中最后的r++
            //     w=保留元素的大小
            // r!=size 表示可能出错了
            if (r != size) { // 这种情况何时出现?出现异常?
                // 移动list,填补删除的空白位置
                System.arraycopy(elementData, r,
                                 elementData, w,
                        size - r);
                w += size - r;
            }
            //如果w==size:表示全部元素都保留了,所以也就没有删除操作发生,所以会返回false;反之,返回true,并更改数组
            //而 w!=size;即使try抛出异常,也能正常处理异常抛出前的操作,因为w始终要为保留的前半部分,数组也不会因此乱序
            if (w != size) { // 没删完,把不需要的元素置为null
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

    /**
     * 保存list实例的状态到流中
     * @param s
     * @throws java.io.IOException
     */
    private void writeObject(java.io.objectOutputStream s)
        throws java.io.IOException{
        // 写入隐藏状态
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // 写入容量大小,用于clone
        s.writeInt(size);

        // 按顺序写入元素
        for(int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }
        if(modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * 从反序列化中重构ArrayList实例
     * @param s
     * @throws java.io.IOException
     * @throws ClassNotFoundException
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException{
        elementData = EMPTY_ELEMENTDATA;

        // 读取隐藏状态
        s.defaultReadObject();

        // 读取size
        s.readInt();

        if(size > 0) {
            // 类似clone(), 基于前面的size而不是容量分配数组
            int capacity = calculateCapacity(elementData, size);
            SharedSecrets.getJavaIOAccess().checkArray(s, Object[].class, capacity);
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // 按顺序读取元素
            for (int i=0; i<size; i++)
                a[i] = s.readObject();
        }
    }

    /**
     * 返回一个从index开始的list迭代器
     * @param index
     * @return
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * 返回一个list迭代器
     * @return
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 返回一个iterator
     * @return
     */
    public Iterator<E> iterator() {
        return new Itr();
    }
    /**
     * Itr是AbstractList.Itr的优化版本
     * 为什么会报ConcurrentModificationException异常?
     * 1. Iterator 是工作在一个独立的线程中,并且拥有一个 mutex(互斥) 锁。
     * 2. Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,
     * 这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,
     * 3. 所以按照 fail-fast(快速失败,一种Java集合的错误检测机制) 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
     * 4. 所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。
     * 但你可以使用 Iterator 本身的方法 remove() 来删除对象,
     * 5. Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
     */
    private class Itr implements Iterator<E> {
        int cursor;             // 下一个返回元素的索引
        int lastRet = -1;       // 最后一个元素返回的索引 -1 if no such
        int expectedModCount = modCount;

        Itr() {}

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

        @SuppressWarnings("unchecked")
        public E next() {
            rangeForComodification();
            int i = cursor;  //i当前元素的索引
            if (i >= size)  // 第一次检查:检查下标是否越界
                throw new NoSuchElementException();
            Object[] elementData = MyArrayList.this.elementData;
            if (i >= elementData.length)  // 第二次检查,list集合中元素数量是否发生变化
                throw new ConcurrentModificationException();
            cursor = i + 1; // 更新下一个元素的索引
            return (E) elementData[lastRet = i]; // 将当前迭代i看做是最后一个元素索引,并返回当前i索引代表的元素值
        }

        public void remove() {
            if (lastRet < 0)  // 检查下标,如果小于0,说明为空
                throw new IllegalStateException();
            checkForComodification();

            try {
                MyArrayList.this.remove(lastRet);  // 调用ArrayList的删除方法
                //由于cursor比lastRet大1,所有这行代码是指指针往回移动一位
                cursor = lastRet;
                //将最后一个元素返回的索引重置为-1
                lastRet = -1;
                //重新设置了expectedModCount的值,避免了ConcurrentModificationException的产生
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        /**
         * jdk 1.8中使用的方法
         * 将list中的所有元素都给了consumer,可以使用这个方法来取出元素
         * @param consumer
         */
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = MyArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = MyArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }

            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        /**
         * 检查modCount是否等于expectedModCount
         * 在迭代时list集合的元素数量发生变化时会造成这两个值不相等
         * 所以 Iterator 在工作的时候是不允许被迭代的对象被改变的
         * 不然会报异常
         */
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    /*------------------------------------- Itr 结束 -------------------------------------------*/

    /**
     * AbstractList.ListItr 的优化版本
     * ListIterator 与普通的 Iterator 的区别:
     * - 它可以进行双向移动,而普通的迭代器只能单向移动
     * - 它可以添加元素(有 add() 方法),而后者不行
     */
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        /**
         * 是否有前一个元素
         * @return
         */
        public boolean hasPrevious() {
            return cursor != 0;
        }

        /**
         * 获取下一个元素的索引
         * @return
         */
        public int nextIndex() {
            return cursor;
        }

        /**
         * 获取cursor前一个元素的索引,注意cursor是一个元素返回的索引!!!
         * - 是 cursor 前一个,而不是当前元素前一个的索引。
         * - 若调用 next() 后马上调用该方法,则返回的是当前元素的索引。
         * - 若调用 next() 后想获取当前元素前一个元素的索引,需要连续调用两次该方法。
         * @return
         */
        public int previousIndex() {
            return cursor - 1;
        }

        /**
         * 返回前一个元素
         * @return
         */
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0) // 是否是第一个,第一个的前一个为空
                throw new NoSuchElementException();
            Object[] elementData = MyArrayList.this.elementData;
            if (i >= elementData.length)  //下标检查
                throw new ConcurrentModificationException();
            cursor = i;  // 更改cursor值
            return (E)elementData[lastRet = i]; //返回 cursor 前一元素
        }

        /**
         * 将数组的最后一个元素,设置成元素e
         * @param e
         */
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                MyArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        /**
         * 添加元素
         * @param e
         */
        public void add(E e) {
            checkForComodification();
            try {
                int i = cursor;  //当前元素的索引后移一位
                MyArrayList.this.add(i, e); // 在i位置上添加元素
                cursor = i + 1; // 更新cursor
                lastRet = -1;   //
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }
    /*------------------------------------- ListItr 结束 -------------------------------------------*/


    /**
     * 获取从 fromIndex 到 toIndex 之间的子集合(左闭右开区间)
     * - 若 fromIndex == toIndex,则返回的空集合
     * - 对该子集合的操作,会影响原有集合
     * - 当调用了 subList() 后,若对原有集合进行删除操作(删除subList 中的首个元素)时,
     *   会抛出异常 java.util.ConcurrentModificationException
     *   这个和Itr的原因差不多由于modCount发生了改变,对集合的操作需要用子集合提供的方法
     * - 该子集合支持所有的集合操作
     * 原因看 SubList 内部类的构造函数就可以知道
     * @param fromIndex
     * @param toIndex
     * @return
     */
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

    /**
     * 检查索引的合法性
     * @param fromIndex
     * @param toIndex
     * @param size
     */
    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size) //由于是左闭右开的,所以toIndex可以等于size
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IndexOutOfBoundsException("fromIndex(" + fromIndex +
                    ") > toIndex" + toIndex);
    }

    /**
     * 私有类
     * 嵌套内部类:也实现了 RandomAccess,提供快速随机访问特性
     * 这个是通过映射来实现的
     */
    private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;   // 实际传入ArrayList本身
        private final int parentOffset;         // 相当于父集合的偏移量,其实就fromIndex
        private final int offset;               // 偏移量,默认是0

        int size;                               // SubList中的元素个数

        /**
         * 看到这部分,就理解为什么对 SubList 的操作,会影响父集合--->
         * 因为子集合的处理,仅仅是给出了一个映射到父集合相应区间的引用
         * 再加上 final,的修饰,就能明白为什么进行了截取子集合操作后,
         * 父集合不能删除 SubList 中的首个元素了--->offset 不能更改
         * @param parent
         * @param offset
         * @param fromIndex
         * @param toIndex
         */
        SubList(AbstractList<E> parent, int offset,
                int fromIndex, int toIndex) {
            this.parent = parent;
            this.parentOffset = offset;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = MyArrayList.this.modCount;
        }

        /**
         * 修改某索引处为新值,返回旧值
         * @param index
         * @param e
         * @return
         */
        public E set(int index, E e) {
            rangeCheck(index);
            checkForComodification();
            //从这一条语句可以看出:对子类添加元素,是直接操作父类添加的
            E oldValue = MyArrayList.this.elementData(offset + index);
            MyArrayList.this.elementData[offset + index] = e;
            return oldValue;
        }

        /**
         * 获取指定索引处的值
         * @param index
         * @return
         */
        public E get(int index) {
            rangeCheck(index);
            checkForComodification();
            return MyArrayList.this.elementData(offset + index);
        }

        /**
         * 返回元素的数量
         * @return
         */
        public int size() {
            checkForComodification();
            return this.size;
        }

        /**
         * 指定位置添加元素
         * @param index
         * @param e
         */
        public void add(int index, E e) {
            rangeCheck(index);
            checkForComodification();
            //从这里可以看出,先通过index拿到在原来数组上的索引,再调用父类的添加方法实现添加
            parent.add(parentOffset + index, e);
            this.modCount = parent.modCount;
            this.size++;
        }

        /**
         * 删除指定索引处的值
         * @param index
         * @return
         */
        public E remove(int index) {
            rangeCheck(index);
            checkForComodification();
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

        /**
         * 移除subList中的[fromIndex,toIndex)之间的元素
         * @param fromIndex
         * @param toIndex
         */
        protected void removeRange(int fromIndex, int toIndex) {
            checkForModification();
            parent.removeRange(parentOffset + fromIndex,
                               parentOffset + toIndex);
            this.modCount = parent.modCount;
            this.size -= toIndex - fromIndex;
        }

        /**
         * 在subList末尾添加给定集合中的所有元素
         * @param c
         * @return
         */
        public boolean addAll(Collection<? extends E> c) {
            return addAll(this.size, c);
        }

        /**
         * 添加给定集合所有元素到指定index
         * @param index
         * @param c
         * @return
         */
        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;
        }

        /**
         * subList中的迭代器
         * @return
         */
        public Iterator<E> iterator() {
            return listIterator();
        }

        /**
         * 返回从指定索引开始到结束的带有元素的list迭代器
         * @param index
         * @return
         */
        public ListIterator<E> listIterator(final int index) {
            checkForComodification();
            rangeCheckForAdd(index);
            final int offset = this.offset;

            return new ListIterator<E>() {
                int cursor = index;
                int lastRet = -1; //最后一个元素的下标
                int expectedModCount = MyArrayList.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[] element = MyArrayList.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 = MyArrayList.this.elementData;
                    if (offset + 1 >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i;
                    return (E) elementData[offset + (last = 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 = MyArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

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

                    try {
                        MyArrayList.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 = MyArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

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

        public List<E> subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new SubList(this, offset, fromIndex, toIndex);
        }

        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 (MyArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
        }

        /**
         * subList方法:获取一个分割器
         * - fail-fast
         * - late-binding:后期绑定
         * - java8 开始提供
         */
        public Spliterator<E> spliterator() {
            checkForComodification();
            return new ArrayListSpliterator<E>(MyArrayList.this, offset,
                    offset + this.size, this.modCount);
        }
    }
    /*------------------SubList结束-------------------------------*/


    @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]); //这里将所有元素都接受到Consumer中了,所有可以使用1.8中的方法直接获取每一个元素
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
    /**
     * 获取一个分割器
     * - fail-fast 机制和itr,subList一个机制
     * - late-binding:后期绑定
     * - java8 开始提供
     * @return a {@code Spliterator} over the elements in this list
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new ArrayListSpliterator<>(this, 0, -1, 0);
    }

    /**
     * 基于索引的、二分的、懒加载的分割器
     * @param <E>
     */
    static final class ArrayListSpliterator<E> implements Spliterator<E> {

        private final MyArrayList<E> list;
        private int index;                   //起始位置(包含),advance/split操作时会修改
        private int fence;                   //结束位置(不包含),-1 表示到最后一个元素
        private int expentedModCount;        //用于存放list的modCount
        //默认的起始位置是0,默认的结束位置是-1
        ArrayListSpliterator(MyArrayList<E> list, int origin, int fence, int expentedModCount) {
            this.list = list;
            this.index= origin;
            this.fence = fence;
            this.expentedModCount = expentedModCount;
        }
        //在第一次使用时实例化结束位置
        private int getFence() {
            int hi;
            MyArrayList<E> lst;
            //fence<0时(第一次初始化时,fence才会小于0):
            if ((hi = fence) < 0){
                //如果list集合中没有元素
                if ((lst = list) == null)
                    //list 为 null时,fence=0
                    hi = fence = 0;
                else {
                    expentedModCount = lst.modCount;
                    //否则,fence = list的长度
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        /**
         * 分割list,返回一个新分割出的spliterator实例
         * 相当于二分法,这个方法会递归
         * 1.ArrayListSpliterator本质上还是对原list进行操作,只是通过index和fence来控制每次处理范围
         * 2.也可以得出,ArrayListSpliterator在遍历元素时,不能对list进行结构变更操作,否则抛错。
         * @return
         */
        public ArrayListSpliterator<E> trySplit() {
            //hi:结束位置(不包括)  lo:开始位置   mid:中间位置
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            //当lo>=mid,表示不能在分割,返回null
            //当lo<mid时,可分割,切割(lo,mid)出去,同时更新index=mid
            /**如:   | 0 | 1 | 2 | 3 | 4 | 5 |    数组长度为6 的进行 split
             *   结束角标 hi:6    开始角标lo:0    mid:3    lo<mid
             *   [0,3)  同时 lo:3   hi:6    mid:4
             *   [3,4)  同时  lo:4   hi:6   mid:5
             *   [4,5)  同时   lo:5   hid:6   mid:5
             *   null
             */
            return (lo >= mid)
                    ? null
                    : new ArrayListSpliterator<>(list, lo, index=mid, expentedModCount);
        }

        //返回true 时,只表示可能还有元素未处理
        //返回false 时,没有剩余元素处理了
        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 != expentedModCount) // 遍历时,结构发生变更,抛出异常
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        /**
         * 顺序遍历处理所有剩下的元素
         * Consumer类型,传入值处理
         * @param action
         */
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi, mc;
            MyArrayList<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            //如果list不为空 而且  list中的元素不为空
            if ((lst = list) != null && (a = lst.elementData) != null) {
                //当fence<0时,表示fence和expectedModCount未初始化,可以思考一下这里能否直接调用getFence()?
                if ((hi = fence) < 0) {
                    mc = lst.modCount;
                    hi = lst.size;  //由于上面判断过了,可以直接将lst大小给hi(不包括)
                }
                else
                    mc = expentedModCount;
                //将所有元素给Consumer
                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)
                        return ;
                }
            }
            throw new ConcurrentModificationException();
        }

        /**
         * 估算大小
         * @return
         */
        public long estimateSize() {
            return (long) (getFence() - index);
        }

        /**
         * 打上特征值:可以返回size
         * @return
         */
        public int characteristics() {
            //顺序,大小,子大小
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

    /**
     * 根据Predicate条件来移除元素
     * 将所有元素依次根据filter的条件判断
     * Predicate 是 传入元素 返回 boolean 类型的接口
     * @param filter
     * @return
     */
    @Override
    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); //将满足条件的角标存放到set中
                removeCount++; //移除set的数量
            }
        }
        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是[0,size)中不是set集合中的角标
                elementData[j] = elementData[i]; //新元素
            }
            //将空元素置空
            for(int k=newSize; k < size; k++) {
                elementData[k] = null;
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }
        return anyToRemove;
    }

    /**
     * UnaryOperator 接受一个什么类型的参数,返回一个什么类型的参数
     * 对数组中的每一个元素进行一系列的操作,返回同样的元素,
     * 如果 List<Student> lists  将list集合中的每一个student姓名改为张三
     * 使用这个方法就非常方便
     * @param operator
     */
    @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++) {
            //取出每一个元素给operator的apply方法
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        modCount++;
    }

    /**
     * 根据 Comparator条件进行排序
     * @param c
     */
    @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++;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值