AbstractList源码分析(JDK1.8)屌丝版

/*
 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.util;

/**
 * This class provides a skeletal implementation of the {@link List}
 * interface to minimize the effort required to implement this interface
 * backed by a "random access" data store (such as an array).  For sequential
 * access data (such as a linked list), {@link AbstractSequentialList} should
 * be used in preference to this class.
 *
 * <p>To implement an unmodifiable list, the programmer needs only to extend
 * this class and provide implementations for the {@link #get(int)} and
 * {@link List#size() size()} methods.
 *
 * <p>To implement a modifiable list, the programmer must additionally
 * override the {@link #set(int, Object) set(int, E)} method (which otherwise
 * throws an {@code UnsupportedOperationException}).  If the list is
 * variable-size the programmer must additionally override the
 * {@link #add(int, Object) add(int, E)} and {@link #remove(int)} methods.
 *
 * <p>The programmer should generally provide a void (no argument) and collection
 * constructor, as per the recommendation in the {@link Collection} interface
 * specification.
 *
 * <p>Unlike the other abstract collection implementations, the programmer does
 * <i>not</i> have to provide an iterator implementation; the iterator and
 * list iterator are implemented by this class, on top of the "random access"
 * methods:
 * {@link #get(int)},
 * {@link #set(int, Object) set(int, E)},
 * {@link #add(int, Object) add(int, E)} and
 * {@link #remove(int)}.
 *
 * <p>The documentation for each non-abstract method in this class describes its
 * implementation in detail.  Each of these methods may be overridden if the
 * collection being implemented admits a more efficient implementation.
 *
 * <p>This class is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @since 1.2
 */

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { //谁让ArrayList扩展了AbstractList,所以,看看基类也是好事
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically //我们看它扩展了AbstractCollection,另外也注明实现了List,好吧,反正基类与实现类都写实现了同一个接口,也没关系嘛
     * implicit.) //就是要便于阅读,就是要任性的写明implements List
     */
    protected AbstractList() { //默认的构造方法,好吧,protected,除非你扩展我,不然在其它包没戏调我
    }

    /**
     * Appends the specified element to the end of this list (optional
     * operation).
     *
     * <p>Lists that support this operation may place limitations on what
     * elements may be added to this list.  In particular, some
     * lists will refuse to add null elements, and others will impose
     * restrictions on the type of elements that may be added.  List
     * classes should clearly specify in their documentation any restrictions
     * on what elements may be added.
     *
     * <p>This implementation calls {@code add(size(), e)}.
     *
     * <p>Note that this implementation throws an
     * {@code UnsupportedOperationException} unless
     * {@link #add(int, Object) add(int, E)} is overridden.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     * @throws UnsupportedOperationException if the {@code add} operation
     *         is not supported by this list
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this list
     * @throws NullPointerException if the specified element is null and this
     *         list does not permit null elements
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this list
     */
    public boolean add(E e) { //加入一个元素,嘿嘿,是在线性表尾部加入
        add(size(), e); //当然是调用指定index的方法,传入size,还有元素即可,假设一共5个元素,那么下标5一定是空的喽
        return true; //走到这里,就代表添加元素成功了。
    }

    /**
     * {@inheritDoc}
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    abstract public E get(int index); //根据下标,得到元素,交给扩展类去实现吧

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E set(int index, E element) { //哎呀,我去基类的实现,就是抛个异常撒,这是替换元素的方法嘛
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */ 
    public void add(int index, E element) { //这个添加元素到指定位置的方法,也是这样
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E remove(int index) { //醉了,这里也一样,干脆直接抛异常好了,要是不支持的话,支持,就只能去重写,作者牛逼
        throw new UnsupportedOperationException();
    }


    // Search Operations

    /**
     * {@inheritDoc}
     *
     * <p>This implementation first gets a list iterator (with
     * {@code listIterator()}).  Then, it iterates over the list until the
     * specified element is found or the end of the list is reached.
     *
     * @throws ClassCastException   {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public int indexOf(Object o) { //返回某个元素的下标
        ListIterator<E> it = listIterator(); //好吧,用的ListIterator迭代器
        if (o==null) { //元素为null,在这里做处理
            while (it.hasNext()) //这里先判断是否有元素
                if (it.next()==null) //要是拿到的元素为null //毕竟next返回当前元素,并让cursor已经+1了
                    return it.previousIndex(); //就返回上一个元素的下标,毕竟cursor+1了嘛,previousIndex是cursor-1
        } else { //如果元素不为null,在这里处理
            while (it.hasNext()) //如果包含有元素
                if (o.equals(it.next())) //元素equals相等的话
                    return it.previousIndex(); //老规矩,返回这个元素的下标 previoursIndex是cursor-1的结果
        }
        return -1; //没有符合条件的元素,就返回-1了
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation first gets a list iterator that points to the end
     * of the list (with {@code listIterator(size())}).  Then, it iterates
     * backwards over the list until the specified element is found, or the
     * beginning of the list is reached.
     *
     * @throws ClassCastException   {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public int lastIndexOf(Object o) { //返回最后出现的元素的下标,还是作者牛逼,从线性表尾部开始向前遍历,那肯定第一个匹配的元素,也是最后一次出现的下标哈
        ListIterator<E> it = listIterator(size()); //先从尾部开始,就取线性表长度,为指定cursor嘛 
        if (o==null) { //还是先对null元素开始做,没办法,List支持null元素的添加
            while (it.hasPrevious()) //先判断有没有上一个元素,其实cursor!= 0,那就是有嘛,哈哈
                if (it.previous()==null) //取出来,判断
                    return it.nextIndex(); //返回下标
        } else { //
            while (it.hasPrevious()) //好吧,对于Object元素的处理,判断是否还有元素呢?只要cursor不小于0,那就是有了
                if (o.equals(it.previous())) //元素的对比,还是通过equals进行的,赞
                    return it.nextIndex(); //返回该元素从尾部第一次出现时的下标
        }
        return -1; //找不到该元素的话,返回-1
    }


    // Bulk Operations

    /**
     * Removes all of the elements from this list (optional operation).
     * The list will be empty after this call returns.
     *
     * <p>This implementation calls {@code removeRange(0, size())}.
     *
     * <p>Note that this implementation throws an
     * {@code UnsupportedOperationException} unless {@code remove(int
     * index)} or {@code removeRange(int fromIndex, int toIndex)} is
     * overridden.
     *
     * @throws UnsupportedOperationException if the {@code clear} operation
     *         is not supported by this list
     */
    public void clear() { //清除所有元素
        removeRange(0, size());//从下标0一直到size处(不含size()的下标哈,一般都是不含截止下标的元素)
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation gets an iterator over the specified collection
     * and iterates over it, inserting the elements obtained from the
     * iterator into this list at the appropriate position, one at a time,
     * using {@code add(int, E)}.
     * Many implementations will override this method for efficiency.
     *
     * <p>Note that this implementation throws an
     * {@code UnsupportedOperationException} unless
     * {@link #add(int, Object) add(int, E)} is overridden.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */ 
    public boolean addAll(int index, Collection<? extends E> c) { //从下标index处,添加一个List的所有元素进去
        rangeCheckForAdd(index); //还是先检查下标符合不符合范围
        boolean modified = false; //标志位,用来干啥的?用来返回的,代表是否发生修改情况
        for (E e : c) { //遍历List
            add(index++, e); //开始添加元素拉
            modified = true;//只要添加成功一个元素,这边就被赋值为true了
        }
        return modified; //返回修改情况
    }


    // Iterators

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     *
     * <p>This implementation returns a straightforward implementation of the
     * iterator interface, relying on the backing list's {@code size()},
     * {@code get(int)}, and {@code remove(int)} methods.
     *
     * <p>Note that the iterator returned by this method will throw an
     * {@link UnsupportedOperationException} in response to its
     * {@code remove} method unless the list's {@code remove(int)} method is
     * overridden.
     *
     * <p>This implementation can be made to throw runtime exceptions in the
     * face of concurrent modification, as described in the specification
     * for the (protected) {@link #modCount} field.
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public Iterator<E> iterator() { //返回迭代器,就是Iterator
        return new Itr(); //Itr必须是它的实现类哈
    } 

    /**
     * {@inheritDoc}
     *
     * <p>This implementation returns {@code listIterator(0)}.
     *
     * @see #listIterator(int)
     */
    public ListIterator<E> listIterator() {
        return listIterator(0); //返回一个ListIterator迭代器,从下标0开始
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation returns a straightforward implementation of the
     * {@code ListIterator} interface that extends the implementation of the
     * {@code Iterator} interface returned by the {@code iterator()} method.
     * The {@code ListIterator} implementation relies on the backing list's
     * {@code get(int)}, {@code set(int, E)}, {@code add(int, E)}
     * and {@code remove(int)} methods.
     *
     * <p>Note that the list iterator returned by this implementation will
     * throw an {@link UnsupportedOperationException} in response to its
     * {@code remove}, {@code set} and {@code add} methods unless the
     * list's {@code remove(int)}, {@code set(int, E)}, and
     * {@code add(int, E)} methods are overridden.
     *
     * <p>This implementation can be made to throw runtime exceptions in the
     * face of concurrent modification, as described in the specification for
     * the (protected) {@link #modCount} field.
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public ListIterator<E> listIterator(final int index) { //返回一个指定index开始的的ListIterator
        rangeCheckForAdd(index); //必须先检查下标

        return new ListItr(index); //返回该迭代器
    }

    private class Itr implements Iterator<E> { //必须的必,Itr又见面了,我们是普通内部类
        /**
         * Index of element to be returned by subsequent call to next.
         */
        int cursor = 0; //调用next后,随后返回的下标,……翻译的生硬……

        /**
         * Index of element returned by most recent call to next or
         * previous.  Reset to -1 if this element is deleted by a call
         * to remove.
         */
        int lastRet = -1; //调用next、previous,都会更新该下标值,当调用remove元素,就会重置为-1,代表最后返回的元素下标

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        int expectedModCount = modCount;//将修改次数赋值给预期次数

        public boolean hasNext() { //是否有下一个元素,
            return cursor != size(); //只要cursor不等于线性表长度,就代表还有货
        }

        public E next() {
            checkForComodification(); //检查修改次数,是不是一样呢
            try {
                int i = cursor;//先拿cursor过来
                E next = get(i); //然后把元素取出来 
                lastRet = i; //把最后返回的元素下标,赋值给lastRet
                cursor = i + 1; //嘿嘿 cursor+1
                return next; //返回该元素
            } catch (IndexOutOfBoundsException e) { 
                checkForComodification(); //拿到这个IndexOutOfBoundsException后,再对修改次数做判断
                throw new NoSuchElementException();//抛出NoSuchElementException
            }
        }

        public void remove() { //移除元素的方法
            if (lastRet < 0)
                throw new IllegalStateException(); //抛的就是IllegalStateException
            checkForComodification();//这里再次检查修改次数

            try {
                AbstractList.this.remove(lastRet); //嘿嘿,移除的是,最后返回的元素,
                if (lastRet < cursor) //再次判断一下,醉了
                    cursor--; //cursor要减去1的,哈哈
                lastRet = -1; //这边重置-1了,所以连续调用remove,一定会抛异常嘛
                expectedModCount = modCount;//同步修改次数
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException(); //当捕获到IndexOutOfBoundsException时,抛出ConcurrentModifiationException
            }
        }

        final void checkForComodification() { //检查修改次数的方法,特定整成final的,不让人重写,过分
            if (modCount != expectedModCount) //这俩只要不相等
                throw new ConcurrentModificationException(); //铁定抛出ConcurrentModificationException
        }
    }

    private class ListItr extends Itr implements ListIterator<E> { //好吧,又见到这个ListItr了,对Itr做了一个扩展
        ListItr(int index) {
            cursor = index; //构造方法,支持默认的cursor设置
        }

        public boolean hasPrevious() { //这就是该迭代器的优势,判断是否有上一个元素
            return cursor != 0;
        }

        public E previous() { //返回上一个元素
            checkForComodification(); //检查修改次数有无变化
            try {
                int i = cursor - 1; //获取到当前元素next的上一个元素的下标
                E previous = get(i); //哈哈,要拿到这个元素
                lastRet = cursor = i; //同步一下,更新cursor,更新lastRet
                return previous;//返回该元素
            } catch (IndexOutOfBoundsException e) {
                checkForComodification(); //这边,又先检查一下修改次数的情况
                throw new NoSuchElementException();//然后到这里就要抛出NoSuchElementException了
            }
        }

        public int nextIndex() { //返回next元素的下标
            return cursor; //就是cursor,哈哈
        }

        public int previousIndex() {
            return cursor-1; //返回previous的下标
        }

        public void set(E e) {// 替换方法来了 
            if (lastRet < 0) //从这里的判断,就感觉,替换的就是lastRet下标的元素
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.set(lastRet, e); //果然不错,就是替换的lastRet的元素
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {//添加元素的方法
            checkForComodification();

            try {
                int i = cursor;
                AbstractList.this.add(i, e); //在cursor处添加元素
                lastRet = -1; //上面没交代清除,添加元素,也会使lastRet重置为-1
                cursor = i + 1; cursor还要+1哈
                expectedModCount = modCount; //同步修改次数
            } catch (IndexOutOfBoundsException ex) { //醉了,捕获InexOutOfBoundsException
                throw new ConcurrentModificationException();//抛出ConcurrentModificationException
            }
        }
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation returns a list that subclasses
     * {@code AbstractList}.  The subclass stores, in private fields, the
     * offset of the subList within the backing list, the size of the subList
     * (which can change over its lifetime), and the expected
     * {@code modCount} value of the backing list.  There are two variants
     * of the subclass, one of which implements {@code RandomAccess}.
     * If this list implements {@code RandomAccess} the returned list will
     * be an instance of the subclass that implements {@code RandomAccess}.
     *
     * <p>The subclass's {@code set(int, E)}, {@code get(int)},
     * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int,
     * Collection)} and {@code removeRange(int, int)} methods all
     * delegate to the corresponding methods on the backing abstract list,
     * after bounds-checking the index and adjusting for the offset.  The
     * {@code addAll(Collection c)} method merely returns {@code addAll(size,
     * c)}.
     *
     * <p>The {@code listIterator(int)} method returns a "wrapper object"
     * over a list iterator on the backing list, which is created with the
     * corresponding method on the backing list.  The {@code iterator} method
     * merely returns {@code listIterator()}, and the {@code size} method
     * merely returns the subclass's {@code size} field.
     *
     * <p>All methods first check to see if the actual {@code modCount} of
     * the backing list is equal to its expected value, and throw a
     * {@code ConcurrentModificationException} if it is not.
     *
     * @throws IndexOutOfBoundsException if an endpoint index value is out of range
     *         {@code (fromIndex < 0 || toIndex > size)}
     * @throws IllegalArgumentException if the endpoint indices are out of order
     *         {@code (fromIndex > toIndex)}
     */
    public List<E> subList(int fromIndex, int toIndex) { //subList方法撒,返回SubList对象,轻松吧
        return (this instanceof RandomAccess ? //这里做了个判断,当前对象是否为RandomAccess的实现类的对象
                new RandomAccessSubList<>(this, fromIndex, toIndex) : //如果是 返回RandomAccessSubList对象
                new SubList<>(this, fromIndex, toIndex)); //否则,返回SubList对象
    }

    // Comparison and hashing

    /**
     * Compares the specified object with this list for equality.  Returns
     * {@code true} if and only if the specified object is also a list, both
     * lists have the same size, and all corresponding pairs of elements in
     * the two lists are <i>equal</i>.  (Two elements {@code e1} and
     * {@code e2} are <i>equal</i> if {@code (e1==null ? e2==null :
     * e1.equals(e2))}.)  In other words, two lists are defined to be
     * equal if they contain the same elements in the same order.<p>
     *
     * This implementation first checks if the specified object is this
     * list. If so, it returns {@code true}; if not, it checks if the
     * specified object is a list. If not, it returns {@code false}; if so,
     * it iterates over both lists, comparing corresponding pairs of elements.
     * If any comparison returns {@code false}, this method returns
     * {@code false}.  If either iterator runs out of elements before the
     * other it returns {@code false} (as the lists are of unequal length);
     * otherwise it returns {@code true} when the iterations complete.
     *
     * @param o the object to be compared for equality with this list
     * @return {@code true} if the specified object is equal to this list
     */
    public boolean equals(Object o) { //重写的equals方法,明显是为了判断List的哦,o也肯定是传进来的List
        if (o == this)
            return true; //嘿嘿,判断 o 与 当前引用(this)是否指向同一个对象,this代表当前对象,其实肯定是它的引用
        if (!(o instanceof List))  //如果o不是List或者List扩展类的对象则返回false
            return false;
 
        ListIterator<E> e1 = listIterator(); //先拿到一个迭代器,是当前List的迭代器
        ListIterator<?> e2 = ((List<?>) o).listIterator(); //强制把o转换为List,再去call它的listIterator方法哈
        while (e1.hasNext() && e2.hasNext()) { //当前List、还有传入的List,两个迭代器,一同判断是否存在与元素
            E o1 = e1.next(); //先拿到当前List的元素
            Object o2 = e2.next(); //再拿到传入List的元素
            if (!(o1==null ? o2==null : o1.equals(o2))) //这里判断厉害了,如果为首个List的元素为null情况
                return false;                           //这里元素不为null时,调用equals方法,进行对比,如果元素equals
        }                                               //相等,则循环继续,如果发现一个元素不相等,就直接返回false
        return !(e1.hasNext() || e2.hasNext()); //这边也厉害了,判断两个List的元素数量是否一致,经过上面循环,如果两个List
    }                                           //都没有元素了,则这里肯定是false的,!false,那就会返回true了,如果两个List元素数量不一致,就一定是false了,不知道为啥,作者不一开始判断数量不一致的问题

    /**
     * Returns the hash code value for this list.
     *
     * <p>This implementation uses exactly the code that is used to define the
     * list hash function in the documentation for the {@link List#hashCode}
     * method.
     *
     * @return the hash code value for this list
     */
    public int hashCode() { //hashCode方法,也重写了撒
        int hashCode = 1; //整个hashCode的局部变量整型值
        for (E e : this) //来吧,遍历当前List的元素
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); //为啥要乘以31啊,这个算法厉害了,所有元素的hashCode值构成了List的hashCode值,醉了
        return hashCode;
    }

    /**
     * Removes from this list all of the elements whose index is between
     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
     * Shifts any succeeding elements to the left (reduces their index).
     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
     * (If {@code toIndex==fromIndex}, this operation has no effect.)
     *
     * <p>This method is called by the {@code clear} operation on this list
     * and its subLists.  Overriding this method to take advantage of
     * the internals of the list implementation can <i>substantially</i>
     * improve the performance of the {@code clear} operation on this list
     * and its subLists.
     *
     * <p>This implementation gets a list iterator positioned before
     * {@code fromIndex}, and repeatedly calls {@code ListIterator.next}
     * followed by {@code ListIterator.remove} until the entire range has
     * been removed.  <b>Note: if {@code ListIterator.remove} requires linear
     * time, this implementation requires quadratic time.</b>
     *
     * @param fromIndex index of first element to be removed
     * @param toIndex index after last element to be removed
     */
    protected void removeRange(int fromIndex, int toIndex) { //开始移除元素的下标fromIndex,结尾下标toIndex(不含该元素)
        ListIterator<E> it = listIterator(fromIndex); //先拿到一个ListIterator迭代器,嘿嘿,cursor的位置是fromIndex
        for (int i=0, n=toIndex-fromIndex; i<n; i++) { //假设from是0,toIndex是18,嘿嘿,那么n就是0-17了,刚好满足拉
            it.next(); //这里呢,next,会记录lastRet
            it.remove(); //remove就是删除lastRet指向的下标,而且还好reset为-1
        }
    }

    /**
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     *
     * <p>This field is used by the iterator and list iterator implementation
     * returned by the {@code iterator} and {@code listIterator} methods.
     * If the value of this field changes unexpectedly, the iterator (or list
     * iterator) will throw a {@code ConcurrentModificationException} in
     * response to the {@code next}, {@code remove}, {@code previous},
     * {@code set} or {@code add} operations.  This provides
     * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
     * the face of concurrent modification during iteration.
     *
     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
     * wishes to provide fail-fast iterators (and list iterators), then it
     * merely has to increment this field in its {@code add(int, E)} and
     * {@code remove(int)} methods (and any other methods that it overrides
     * that result in structural modifications to the list).  A single call to
     * {@code add(int, E)} or {@code remove(int)} must add no more than
     * one to this field, or the iterators (and list iterators) will throw
     * bogus {@code ConcurrentModificationExceptions}.  If an implementation
     * does not wish to provide fail-fast iterators, this field may be
     * ignored.
     */
    protected transient int modCount = 0; //加入transient, modCount不会参与序列化,

    private void rangeCheckForAdd(int index) {//下标检测,嘿嘿
        if (index < 0 || index > size()) 
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

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

class SubList<E> extends AbstractList<E> {
    private final AbstractList<E> l;
    private final int offset;
    private int size;

    SubList(AbstractList<E> list, int fromIndex, int toIndex) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > list.size())
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
        l = list;
        offset = fromIndex;
        size = toIndex - fromIndex;
        this.modCount = l.modCount;
    }

    public E set(int index, E element) {
        rangeCheck(index);
        checkForComodification();
        return l.set(index+offset, element);
    }

    public E get(int index) {
        rangeCheck(index);
        checkForComodification();
        return l.get(index+offset);
    }

    public int size() {
        checkForComodification();
        return size;
    }

    public void add(int index, E element) {
        rangeCheckForAdd(index);
        checkForComodification();
        l.add(index+offset, element);
        this.modCount = l.modCount;
        size++;
    }

    public E remove(int index) {
        rangeCheck(index);
        checkForComodification();
        E result = l.remove(index+offset);
        this.modCount = l.modCount;
        size--;
        return result;
    }

    protected void removeRange(int fromIndex, int toIndex) {
        checkForComodification();
        l.removeRange(fromIndex+offset, toIndex+offset);
        this.modCount = l.modCount;
        size -= (toIndex-fromIndex);
    }

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

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

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

    public Iterator<E> iterator() {
        return listIterator();
    }

    public ListIterator<E> listIterator(final int index) {
        checkForComodification();
        rangeCheckForAdd(index);

        return new ListIterator<E>() {
            private final ListIterator<E> i = l.listIterator(index+offset);

            public boolean hasNext() {
                return nextIndex() < size;
            }

            public E next() {
                if (hasNext())
                    return i.next();
                else
                    throw new NoSuchElementException();
            }

            public boolean hasPrevious() {
                return previousIndex() >= 0;
            }

            public E previous() {
                if (hasPrevious())
                    return i.previous();
                else
                    throw new NoSuchElementException();
            }

            public int nextIndex() {
                return i.nextIndex() - offset;
            }

            public int previousIndex() {
                return i.previousIndex() - offset;
            }

            public void remove() {
                i.remove();
                SubList.this.modCount = l.modCount;
                size--;
            }

            public void set(E e) {
                i.set(e);
            }

            public void add(E e) {
                i.add(e);
                SubList.this.modCount = l.modCount;
                size++;
            }
        };
    }

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

    private void rangeCheck(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

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

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

    private void checkForComodification() {
        if (this.modCount != l.modCount)
            throw new ConcurrentModificationException();
    }
}

class RandomAccessSubList<E> extends SubList<E> implements RandomAccess { //嘿嘿,对SubList做了一个扩展
    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
        super(list, fromIndex, toIndex);
    }

    public List<E> subList(int fromIndex, int toIndex) { //就多了一个这个方法吗?
        return new RandomAccessSubList<>(this, fromIndex, toIndex);
    }
}

猜你喜欢

转载自blog.csdn.net/cadi2011/article/details/80200833