美文网首页
AbstractList

AbstractList

作者: 天堂挽歌 | 来源:发表于2019-08-21 18:40 被阅读0次
/*
 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.util;

/**
 * 这个集合提供了{@link List}接口的骨架。可以在实现这个接口时,需求最小化。如“随机访
 * 问”数据存储(例如数组)。对于顺序数据访问(如linked集合),应优先使用 {@link AbstractSequentialList} 
 *
 * <p>当实现一个不可修改的list,开发者只需要去继承本类,并提供{@link #get(int)}与
 * {@link List#size() size()} 的实现。
 *
 * <p>当实现一个可修改的list,开发者必须重写 {@link #set(int, Object) set(int, E)} 方法(否则它会抛出
 * {@code UnsupportedOperationException})。如果这个list大小可变,开发者必须重
  * 写 {@link #add(int, Object) add(int, E)} 与 {@link #remove(int)} 方法.
 *
 * <p>根据{@link Collection}的规范,推荐开发者通常应该提供一个无参数以及一个collextion参数构
 * 造器。
 *
 * <p>与其他集合的抽象实现不同。开发者不需要去提供迭代其实现;iterator与list iterator已经在
 * 本类中实现,上面的“随机访问”方法: 
 * methods:
 * {@link #get(int)},
 * {@link #set(int, Object) set(int, E)},
 * {@link #add(int, Object) add(int, E)} and
 * {@link #remove(int)}.
 *
 * <p>这个类中的没一个非抽象类的文档描述了实现的细节。当具体的实现类有多个不同的实现
 * 时,本类中的方法可能因此被重写。
 *
 * <p>这个类是
 * <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> {
    /**
     * 唯一的构造器。(由子类构造器调用,通常是隐式的)
     */
    protected AbstractList() {
    }

    /**
     * 添加指定的元素到集合的尾部(可选操作).
     *
     * <p>集合支持限制什么集合可以添加到当前列表的操作。特别的,有些列表会拒绝添加null元
     * 素,以及其他的一些将会在添加时强制限制元素的类型。列表类应该在它们的文档中明确的
     * 指示可以添加的元素的限制。
     *
     * <p>这个实现调用 {@code add(size(), e)}.
     *
     * <p>注意,除非{@link #add(int, Object) add(int, E)} 方法被重写,否则这个实现将会抛
     * 出 {@code UnsupportedOperationException} 。
     *
     * @param e 这个元素将会被追加到当前列表中
     * @return {@code true} 由{@link Collection#add}制定)
     * @throws UnsupportedOperationException 当{@code add}操作不被当前列表支持
     * @throws ClassCastException 当添加指定元素时,此元素的类型被拒绝
     * @throws NullPointerException 如果制定的元素是空的,并且当前集合不允许空元素
     * @throws IllegalArgumentException 当指定元素的某些属性在添加过程中被拒绝时
     */
    public boolean add(E e) {
        add(size(), e);
        return true;
    }

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

    /**
     * {@inheritDoc}
     *
     * <p>这个实现总是抛出异常
     * {@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>这个实现总是抛出异常
     * {@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();
    }


    // 搜索操作

    /**
     * {@inheritDoc}
     *
     * <p>这个实现首先会获取列表的迭代器(使用{@code listIterator()})。然后,他迭代所有元
     * 素,直到指定元素被找到或是到列表的结尾。
     *
     * @throws ClassCastException   {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    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;
    }

    /**
     * {@inheritDoc}
     *
     * <p>这个实现首先会获取索引位于列表结束位置的列表迭代
     * 器(使用 {@code listIterator(size())})。然后,反向遍历列表。直到指定元素被找到或是到达
     * 列表头。
     *
     * @throws ClassCastException   {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    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;
    }


    // 扩展操作

    /**
     * 删除当前列表的全部元素(可选操作).
     * 在调用返回后,这个列表将是空的。
     *
     * <p>这个实现调用{@code removeRange(0, size())}.
     *
     * <p>注意,除非重写{@code remove(int index)}或
     * {@code removeRange(int fromIndex, int toIndex)}方法,否则这个实现会
     * 抛出{@code UnsupportedOperationException}。
     *
     * @throws UnsupportedOperationException 当前列表不支持{@code clear}操作
     */
    public void clear() {
        removeRange(0, size());
    }

    /**
     * {@inheritDoc}
     *
     * <p>这个实现从指定集合中获取一个迭代器并遍历他,使用{@code add(int, E)},一次一个,将
     * 从迭代其中获取的元素插入到当前集合中的适当位置。
     * 和多实现将会使用更高效的方式重新这个方法。
     *
     * <p>注意,除非{@link #add(int, Object) add(int, E)}方法被重写,否则这个方法将会抛出
     * {@code UnsupportedOperationException} 。
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    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;
    }


    // 迭代s

    /**
     * 返回覆盖当前列表全部元素并拥有适当顺序的迭代器。
     *
     * <p>这个实现返回一个iterator的简单实现,依靠列表的{@code size()},{@code get(int)}以
     * 及{@code remove(int)}方法。
     *
     * <p>注意,这个方法返回的迭代器在当前列表没有重写{@code remove(int)} 时,如果调用迭
     * 代器的{@code remove}方法,将会抛出{@link UnsupportedOperationException} 。
     *
     * <p>这个实现会如成员变量 {@link #modCount} 描述的规范一样,在面对并发修改时,会抛出
     * 一个运行时异常。
     *
     * @return 一个覆盖当前列表全部元素并拥有适当顺序的迭代器迭代器
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

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

    /**
     * {@inheritDoc}
     *
     * <p>这个实现返回了一个 {@code ListIterator}接口的简单实现,{@code ListIterator}接口
     * 扩展了{@code iterator()}方法返回的{@code Iterator}实现。
     * {@code ListIterator} 的实现依赖列表的{@code get(int)}, {@code set(int, E)}, {@code add(int, E)}
     * and {@code remove(int)} 方法。
     *
     * <p>注意,当列表没有重写{@code remove(int)}, {@code set(int, E)} 以及
     * {@code add(int, E)方法时调用迭代器的{@code remove}, {@code set} 与 {@code add} 方法,
     * 将会抛出{@link UnsupportedOperationException}。
     *
     * <p>如{@link #modCount} 描述的规范,这个实现(返回的ListIterator)将会在发生并发修改时,抛
     * 出运行是异常。
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);

        return new ListItr(index);
    }
    
    /**
     * 这个实现在官方文档中没有任何类注释 --li.xiaoxi
     */
    private class Itr implements Iterator<E> {
        /**
         * 调用next时,将会被返回的元素索引。
         */
        int cursor = 0;

        /**
         * 最近一次调用next或previous返回元素的索引。当所指的元素使用remove删除,这个是
         * 会冲设为-1。
         */
        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();
        }
    }

    /**
     * 这个实现在官方文档中没有任何类注释 --li.xiaoxi
     */
    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();
            }
        }
    }

    /**
     * {@inheritDoc}
     *
     * <p>这个实现返回一个 {@code AbstractList}的子类列表。这个子类在死有成员储存所以来的
     * 列表的子列表偏移量,子列表的大小(在它的生命周期中可修改),所以来的列表的预
     * 期{@code modCount}。子类有两种变体,一个是实现了{@code RandomAccess}。
     * 如果这个列表实现了 {@code RandomAccess},返回的列表将会是{@code RandomAccess}的
     * 实例。
     *
     * <p>在索引进行边界检查与跳着偏移后,这个子类的{@code set(int, E)}, {@code get(int)},
     * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int,
     * Collection)} 与 {@code removeRange(int, int)} 方法全部委派到所依赖的抽象列表的适当方法。
     *
     * <p>{@code listIterator(int)}方法返回一个覆盖依赖列表的列表迭代器的“包装对象”。这个列表迭
     * 代器是使用所依赖的列表中对应的方法创建的。{@code iterator} 方法仅仅是使用{@code listIterator()}的
     * 返回对象, {@code size}方法仅仅是返回子类的{@code size} 成员变量。
     *
     * <p>全部方法首先会进行检查当前的{@code modCount}与所依赖的列表的值是否相同。当不同时将
     * 抛出 {@code ConcurrentModificationException}。
     *
     * @throws IndexOutOfBoundsException 如果索引超过了{@code (fromIndex < 0 || toIndex > size)}范围
     * @throws IllegalArgumentException 如果索引不正常。如{@code (fromIndex > toIndex)}
     */
    public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<>(this, fromIndex, toIndex) :
                new SubList<>(this, fromIndex, toIndex));
    }

    // 比较与hash

    /**
     * 比较指定对象与当前列表是否相同。当且仅当指定对象也是一个列表,两个列表具有相同的
     * 大小,并且在两个列表的每一个元素都可以使用 <i>equal</i>进行配对时返回{@code true}。 
     * (两个元素 {@code e1}与 {@code e2}<i>是相同的</i> if{@code (e1==null ? e2==null :
     * e1.equals(e2))}.) 换句话说,当两个集合以相同的顺序包含了相同的元素,接可以定义为相等
     *
     * 这个实现首先检查指定对象是否为当前对象,如果是,则返回 {@code true}; 否则它将检查指
     * 定对象是否是一个列表。如果不是,直接返回{@code false};  如果是,这个方法将会遍历两个
     * 列表并比较相应的元素对。如果任何比较返回{@code false},这个方法将返回{@code false}。  如
     * 果任意一个迭代器在另一个迭代器之前耗尽,将返回 {@code false}(如列表的长度不相同)。;其
     * 他情况下,这个方法在迭代完成时返回{@code 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());
    }

    /**
     * 返回当前列表的hash值
     *
     * <p>这个实现使用了定义在{@link List#hashCode}的列表散列方法的文档完全相同。
     *
     * @return 这个列表的散列值
     */
    public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }

    /**
     * 删除集合中位于 包含{@code fromIndex}到不包含 {@code toIndex}间的全部元素。
     * 并将全部后续元素向左移动(减少他们的索引。
     * 调用后,将缩短{@code (toIndex - fromIndex)} 个元素.
     * (如果 {@code toIndex==fromIndex}, 那在本次操作将不会发生改变。)
     *
     * <p>这个方法通过当前列表以及他的子列表的{@code clear}进行调用。
     * 重写这个方法可以对这个列表以及他的子列表在进行 {@code clear}操作时提
     * 供<i>大幅度</i>的性能提升。This method is called by the {@code clear}。
     *
     * <p>这个实现会获取一个位于{@code fromIndex}的列表迭代器,然后重复调
     * 用 {@code ListIterator.next}并接着调用 {@code ListIterator.remove},直到删除范围
     * 内的全部元素。<b>注意:当{@code ListIterator.remove}需要现行时间时,这个实现
     * 需要执行平方时间。</b>
     *
     * @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();
        }
    }

    /**
     * 这个列表已经发生的<i>结构性修改</i>次数。结构修改是指列表的大小发生变化,或
     * 是一些其他方式引起的的扰动,会使正在运行中的迭代器产生错误结果。
     *
     * <p>这个属性用于 {@code iterator} 与 {@code listIterator} 迭代器或列表迭代器的实现。
     * 如果这个属性的值被意外修改,迭代器(或列表迭代器)将会在进行{@code next}, 
     * {@code remove}, {@code previous},{@code set} 或 {@code add}操作时抛出
     * {@code ConcurrentModificationException}。这提供了一个<i>快速失败</i>行为,而不
     * 是在迭代期间发生并发修改时面对未指定行为。
     *
     * <p><b>子类可以选择性的使用这个属性。</b> 当子类希望提供快速失败迭代器(以及列
     * 表迭代器),那么仅仅需要在{@code add(int, E)} 与 {@code remove(int)}方法(以及其他的
     * 会修改列表结构的重写方法)时将这个属性进行自增。每一次调用{@code add(int, E)}或
     * {@code remove(int)} 方法时,判断这个属性是否是有有大于1(包含)的差距,否则迭代器(以及
     * 列表迭代器)将抛出假 {@code 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

      本文链接:https://www.haomeiwen.com/subject/tutmsctx.html