Java集合源码分析(七)-AbstractList

123 阅读9分钟

「这是我参与2022首次更文挑战的第10天,活动详情查看:2022首次更文挑战

源码

package java.util;

/**
 * 这个类提供 List 接口框架实现,尽可能减少实现这个“随机访问”数据存储(例如数组)支持的接口所需的努力
 * 用于顺序访问数据(例如链表),AbstractSequentialList 应该优先于这个类被使用
 * 实现一个不可修改的列表,程序员只需要扩展这个类和提供 get(int) 和 List#size() size() 的方法实现 
 *
 * 实现一个可修改的列表,程序员必须额外重写 #set(int, Object) set(int, E) 方法(否则抛出 UnsupportedOperationException)
 * 如果列表是大小可变的,程序员必须额外重写 #add(int, Object) add(int, E) 和 #remove(int)} 方法
 *
 * 程序员应该普遍提供一个 void(无参)和集合构造器,按照 Collection 接口规范中每个建议
 *
 * 与其他抽象集合实现不同,程序员不需要提供迭代器实现,这个类实现迭代器和列表迭代器,除了“随机访问”方法之外:
 * #get(int),#set(int, Object) set(int, E),#add(int, Object) add(int, E) 和 #remove(int)
 *
 * 这个类每个非抽象方法的文档详细地描述它的实现
 * 如果正在实现的集合允许更高效的实现,每一个这些方法可能被重写
 *
 * 这个类是 Java 集合框架的成员
 *
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @since 1.2
 */

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    /**
     * 唯一构造函数(用于子类构造器调用,通常是隐含的)
     */
    protected AbstractList() {
    }

    /**
     * 追加指定元素到这个列表的末尾(可选操作)
     *
     * 支持这个操作的列表可能会限制哪些可能添加到这个列表的元素
     * 特别是,一些列表将拒绝添加 null 元素,并且其他将对可能添加的元素的类型实现限制
     * List 类应该在它们的文档明确指出对可能添加的元素的任何限制 
     *
     * 这个实现调用 add(size(), e)
     *
     * 请注意,这个实例抛出 UnsupportedOperationException,除非重写 #add(int, Object) add(int, E)
     *
     * @param e 要追加到这个列表的元素
     * @return {@code true} (按照 Collection#add 指定)
     * @throws UnsupportedOperationException 如果这个列表不支持 add 操作
     * @throws ClassCastException 如果指定元素的类阻止它添加到这个集合
     * @throws NullPointerException 如果指定元素是 null,并且这个集合不允许 null 元素
     * @throws IllegalArgumentException 如果元素的某些属性阻止它添加到这个集合
     */
    public boolean add(E e) {
        add(size(), e);
        return true;
    }

    /**
     * @throws IndexOutOfBoundsException
     */
    abstract public E get(int index);

    /**
     * 这个实现经常抛出 UnsupportedOperationException
     *
     * @throws UnsupportedOperationException
     * @throws ClassCastException
     * @throws NullPointerException
     * @throws IllegalArgumentException
     * @throws IndexOutOfBoundsException
     */
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * 这个实现经常抛出 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();
    }

    /**
     * 这个实现经常抛出 UnsupportedOperationException
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }


    // 查询操作

    /**
     * 这个实现首先获取一个列表迭代器(通过  listIterator())
     * 然后,它在列表中迭代,直到指定元素被找到或者到达列表的末尾
     *
     * @throws ClassCastException
     * @throws NullPointerException
     */
    public int indexOf(Object o) {
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return it.previousIndex();
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }

    /**
     * 这个实现首先获取一个纸箱列表末尾的列表迭代器(通过 listIterator(size()))
     * 然后,它向后迭代列表,直到指定元素被找到或者到达列表的开始
     * @throws ClassCastException
     * @throws NullPointerException
     */
    public int lastIndexOf(Object o) {
        ListIterator<E> it = listIterator(size());
        if (o==null) {
            while (it.hasPrevious())
                if (it.previous()==null)
                    return it.nextIndex();
        } else {
            while (it.hasPrevious())
                if (o.equals(it.previous()))
                    return it.nextIndex();
        }
        return -1;
    }


    // 批量操作

    /**
     * 如果这个列表的全部元素(可选操作)
     * 这个方法返回后,这个列表将为空
     *
     * 这个实现调用 removeRange(0, size())
     *
     * 请注意,这个实现抛出 UnsupportedOperationException,除非重写 remove(int index) 或 removeRange(int fromIndex, int toIndex)
     *
     * @throws UnsupportedOperationException 如果这个列表不支持 clear 操作
     */
    public void clear() {
        removeRange(0, size());
    }

    /**
     * 这个实现在指定集合上获取迭代器,并对迭代器进行迭代,每次使用 add(int, E) 插入从迭代器获取的元素到列表合适的位置 
     * 很多实现将重写这个方法提升性能
     *
     * 请注意,这个实现抛出 UnsupportedOperationException,除非重写 #add(int, Object) add(int, E)
     *
     * @throws UnsupportedOperationException
     * @throws ClassCastException
     * @throws NullPointerException
     * @throws IllegalArgumentException
     * @throws IndexOutOfBoundsException
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        boolean modified = false;
        for (E e : c) {
            add(index++, e);
            modified = true;
        }
        return modified;
    }


    // 迭代器

    /**
     * 按正确的顺序返回这个列表的元素的列表迭代器
     *
     * 这个实现返回迭代器接口的直接实现,依赖于支持列表的 size(),get(int),remove(int) 方法
     *
     * 请注意,通过这个方法返回的迭代器将抛出 UnsupportedOperationException 作为它 remove 方法的回应,除非列表的 remove(int) 方法已经被重写
     *
     * 这个实现能够在面对并发修改时抛出运行时异常,像 modCount(受保护)字段的规范描述那样
     *
     * @return 正确的顺序遍历这个列表的元素的迭代器
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * 这个实现返回 listIterator(0)
     *
     * @see #listIterator(int)
     */
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }

    /**
     * 这个实现返回 ListIterator 接口的直接实现,这个实现扩展了 iterator() 方法返回的 Iterator 接口的实现
     * 这个列表迭代器实现依赖于支持列表的 get(int),set(int, E),add(int, E) 和 remove(int) 方法
     * 
     * 请注意,这个实现返回的列表迭代将抛出 UnsupportedOperationException 作为它 remove,set 和 add 方法的回应,除非列表的 remove(int),set(int, E) 和 add(int, E) 方法已经被重写
     * 
     * 这个实现能够在面对并发修改时抛出运行时异常,像 modCount(受保护)字段的规范描述那样
     *
     * @throws IndexOutOfBoundsException
     */
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);

        return new ListItr(index);
    }

    private class Itr implements Iterator<E> {
        /**
         * 后续调用 next 返回的元素的索引 
         */
        int cursor = 0;

        /**
         * 最近调用 next 或 previous 返回元素的索引
         * 如果通过 remove 移除这个元素,重置为 -1
         * Reset to -1 if this element is deleted by a call to remove.
         */
        int lastRet = -1;

        /**
         * 迭代器相信支持列表应该有 modCount 值
         * 如果违反了这个预期,迭代器发现并发修改
         */
        int expectedModCount = modCount;

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

        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

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

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

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

    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            cursor = index;
        }

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

        public E previous() {
            checkForComodification();
            try {
                int i = cursor - 1;
                E previous = get(i);
                lastRet = cursor = i;
                return previous;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public int nextIndex() {
            return cursor;
        }

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

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

            try {
                AbstractList.this.set(lastRet, e);
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

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

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

    /**
     * 这个实现返回 AbstractList 子类的列表
     * 子类在私有字段存储支持列表的子列表的偏移量,子列表的大小(可以在他的生命周期内改变)和支持列表的期望 modCount 值
     * 子类有两个变种,其中一个实现 RandomAccess
     * 如果这个列表实现 RandomAccess,返回列表将是实现 RandomAccess 的子类实例
     *
     * 在索引边界检查和调整偏移量后,子类的 set(int, E), get(int),add(int, E), remove(int),addAll(int, Collection) 和 removeRange(int, int) 方法全部委托给支持抽象列表的相应的方法
     *  addAll(Collection c) 仅仅返回 addAll(size, c)
     * 
     * listIterator(int) 在支持列表的列表迭代器返回一个“包装器对象”,这个迭代器由支持列表上对应方法创建
     * iterator 方法仅仅返回 listIterator(),并且 size 方法仅仅返回子类的 size 字段
     *
     * 全部方法首先检查看支持列表的实际 modCount 等于期望值,如果不等于,抛出 ConcurrentModificationException
     *
     * @throws IndexOutOfBoundsException 如果端点索引值超出范围(fromIndex < 0 || toIndex > size)
     * @throws IllegalArgumentException 如果端点索引值超出顺序(fromIndex > toIndex)
     */
    public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<>(this, fromIndex, toIndex) :
                new SubList<>(this, fromIndex, toIndex));
    }

    // 比较和散列

    /**
     * 比较指定对象和这个列表进行相等比较
     * 当且仅当指定对象同样是一个列表,两个列表有相同大小,并且两个列表相应部分的元素都相等,返回 true(两个对象 e1 和 e2 是相等,如果 (e1==null ? e2==null :e1.equals(e2)))
     * 换句话说,如果两个列表在相同位置包含相同元素,它们定义为相等
     *
     * 这个实现首先检查指定的对象是否在这个列表中
     * 如果在,它返回 true,如果不在,它检查指定的对象是不是列表
     * 如果不是,它返回 false,如果是,它迭代两个列表,比较相应的元素对
     * 如果任何对比返回 false,这个方法返回 false
     * 如果其中一个迭代器在另一个迭代器前用完元素,返回 false(因为列表长度不相等)
     * 否则当迭代完成时,它返回 true
     *
     * @param o 要与这个列表进行相等对比的对象
     * @return {@code true} 如果指定对象与这个列表相同
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;

        ListIterator<E> e1 = listIterator();
        ListIterator<?> e2 = ((List<?>) o).listIterator();
        while (e1.hasNext() && e2.hasNext()) {
            E o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
    }

    /**
     * 返回这个列表的哈希码值
     *
     * 这个实现准确地使用在 List#hashCode 方法文档中用于定义列表哈希函数代码
     *
     * @return 这个列表的哈希码值
     */
    public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }

    /**
     * 从这个列表移除所有索引在 fromIndex(包括)和 toIndex(不包括) 元素
     * 左移任何后续元素(减少他们的索引)
     * 这个调用通过 (toIndex - fromIndex) 元素缩短列表(如果 toIndex==fromIndex,这个操作没有影响)
     *
     * 这个方法被这个列表和它的子列表的 clear 操作调用
     * 重写这个方法通过利用列表实现的内部能够大大的提高在这个列表和它的子列表的 clear 操作的性能 
     *
     * 这个实现将列表迭代器放在 formIndex 之前,并且重复调用 ListIterator.next,跟着 ListIterator.remove,直到整个范围已经被移除
     * 注意:如果 ListIterator.remove 要求线性时间,这个实现要求平方时间
     *
     * @param fromIndex 第一个被移除元素的索引
     * @param toIndex 最后一个被移除元素的下一个索引
     */
    protected void removeRange(int fromIndex, int toIndex) {
        ListIterator<E> it = listIterator(fromIndex);
        for (int i=0, n=toIndex-fromIndex; i<n; i++) {
            it.next();
            it.remove();
        }
    }

    /**
     * 这个列表在结构上已经修改的次数
     * 结构修改是改变列表大小,或用其他方式扰乱它导致迭代过程可能产生不正确的结果
     *
     * 这个字段被 iterator 和 listIterator 方法返回的迭代器和列表迭代器实现使用
     * 如果这个字段的值意外更改,迭代器(或列表迭代器)将抛出 ConcurrentModificationException 作为 next,remove,previous,set 或 add 操作的回应
     * 这个提供快速失败行为,而不是在迭代过程中面对并发修改的不确定行为
     *
     * 通过子类使用这个字段是可选的
     * 如果子类期望提供快速失败迭代器(和列表迭代器),然后,它仅仅需要在它的 add(int, E) 和 remove(int) 方法 (和它重写的任何其他导致列表的结构修改的方法)增加这个字段
     * 单次调用 add(int, E) 或 remove(int) 必须不能添加超过一个到这个字段,否则迭代器(和列表迭代器)将抛出伪 ConcurrentModificationExceptions
     * 如果实现不期望提供快速失败迭代器,这个字段可以忽略
     */
    protected transient int modCount = 0;

    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 {
    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);
    }
}

总结

  • AbstractList
    • public boolean add(E e):追加指定元素到这个列表的末尾
    • abstract public E get(int index)
    • public E set(int index, E element)
    • public E set(int index, E element)
    • public void add(int index, E element)
    • public E remove(int index)
    • 查询操作
      • public int indexOf(Object o)
      • public int lastIndexOf(Object o)
    • 批量操作
      • public void clear()
      • public boolean addAll(int index, Collection<? extends E> c)
    • 迭代器
      • public Iterator<E> iterator()
      • public ListIterator<E> listIterator()
      • public ListIterator<E> listIterator(final int index)
    • Itr
      • public boolean hasNext()
      • public E next()
      • public void remove()
      • final void checkForComodification()
    • ListItr
      • public boolean hasPrevious()
      • public E previous()
      • public int nextIndex()
      • public int previousIndex()
      • public void set(E e)
      • public void add(E e)
    • public List<E> subList(int fromIndex, int toIndex)
    • 比较和散列
      • public boolean equals(Object o)
      • public int hashCode()
    • protected void removeRange(int fromIndex, int toIndex)
    • private void rangeCheckForAdd(int index)
    • private String outOfBoundsMsg(int index)
  • SubList
    • public E set(int index, E element)
    • public E get(int index)
    • public int size()
    • public void add(int index, E element)
    • public E remove(int index)
    • protected void removeRange(int fromIndex, int toIndex)
    • public boolean addAll(Collection<? extends E> c)
    • public boolean addAll(int index, Collection<? extends E> c)
    • public Iterator<E> iterator()
    • public ListIterator<E> listIterator(final int index)
    • public List<E> subList(int fromIndex, int toIndex)
    • private void rangeCheck(int index)
    • private void rangeCheckForAdd(int index)
    • private String outOfBoundsMsg(int index)
    • private void checkForComodification()
  • RandomAccessSubList
    • public List<E> subList(int fromIndex, int toIndex)