zoukankan      html  css  js  c++  java
  • AbstractList源码阅读

    前言

    AbstractList是实现List接口的抽象类,AbstractList抽象类与List接口的关系类似于AbstractCollection抽象类与Collection接口的关系。AbstractList与AbstractCollection一样,也是通过提供一些方法的默认实现,简化我们编写List接口的列表类所需付出的努力。

    实现列表类的需要记住:

    1)要想实现一个不可修改的集合,只需要继承这个类,并且实现get(int)、size()方法;
    2)要想实现一个可以修改的集合,还必须重写set(int, E)方法,该方法默认抛出一个异常。如果集合是可动态调整大小的,还必须重写add(int, E),remove(int)方法

    一、类定义

    public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>

    除了实现List接口,AbstractList还继承了AbstractCollection抽象类。

    二、方法定义

    (一)构造方法

        protected AbstractList() {
        }

    提供一个空构造方法,给子类的构造方法调用(通常是隐式调用)

    (二)元素的增删改查

    (1)

        public boolean add(E e) {
            add(size(), e);
            return true;
        }

    添加指定元素到列表末端。此方法有可能抛出IndexOutOfBoundsException异常。

    方法内部是通过调用add(int, E)方法实现的。

    (2)

        public void add(int index, E element) {
            throw new UnsupportedOperationException();
        }

    添加指定元素到列表的指定位置处。

    方法内部默认抛出UnsupportedOperationException。正如前言所讲,如果我们要实现一个不可修改的列表类,则当调用添加方法时,则抛出不支持添加操作的异常;如果我们要实现一个可以修改的列表类,则必须重写此方法。重写此方法之后,此方法在调用过程中有可能抛出ClassCastException、NullPointerException、IllegalArgumentException、IndexOutOfBoundsException等异常。

    (3)

        public E remove(int index) {
            throw new UnsupportedOperationException();
        }

    删除列表中指定位置的元素。

    方法内部默认抛出UnsupportedOperationException。原因同上。

    (4)

        public E set(int index, E element) {
            throw new UnsupportedOperationException();
        }

    用指定元素更新列表中指定位置处的元素

    方法内部默认抛出UnsupportedOperationException。同上面一样,如果我们要实现一个不可修改的列表类,那么无需实现此方法;反之,要重写此方法。重写此方法之后,此方法还可能抛出ClassCastException、NullPointerException、IllegalArgumentException、IndexOutOfBoundsException等异常。

    (5)

    abstract public E get(int index);

    查找列表指定位置处的元素。此方法有可能抛出IndexOutOfBoundsException异常。

    (6)

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

    查找指定元素在列表中第一次出现的索引。

    通过列表迭代器的迭代实现。

    (7)

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

    查找指定元素在列表中最后一次出现的索引。

    通过列表迭代器迭代实现。

    (三)批量操作

    (1)

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

    添加指定集合的所有元素到列表中。

    首先通过rangeCheckForAdd()方法判断插入位置是否合法,合法则添加元素;否则抛出异常。

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

    当index超出范围,rangeCheckForAdd()方法抛出IndexOutOfBoundsException异常。

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

    抛出异常时,使用outOfBoundsMsg()方法提示异常具体信息。

    (2)

        public void clear() {
            removeRange(0, size());
        }

    清空列表,即,删除列表所有元素

    内部是通过removeRange()方法实现的

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

    (四)相等与哈希

    (1)

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

    判断列表与指定对象是否相等,这里判断的是值相等,而不是同一个对象。

    判等逻辑如下:

    1)如果两个引用指向的对象是同一个对象,那么值肯定相等,返回true;否则,继续判断

    2)如果指定对象不是列表,如指定对象是set集合,那么返回false;否则,继续判断

    3)获取列表、指定对象的列表迭代器,遍历每个元素,并判断相同位置的元素值是否相等,如果有一个不等,则返回false;否则,说明其中一个迭代器的所有元素在另一个迭代器中出现,且出现的位置相同,如果此时不存在其中一个迭代器剩下元素,那直接返回true

    (2)

        public int hashCode() {
            int hashCode = 1;
            for (E e : this)
                hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
            return hashCode;
        }

    得到列表的哈希码值

    方法内部实现是通过遍历列表的每一个元素,得到每个元素的哈希码值(若元素为null,则哈希码值为0;若不为null,则通过hashCode()方法获取元素的哈希码值),然后按照hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); 的规则计算列表的哈希码值,其中初始hashCode=1。当所有元素遍历完毕,最终的hashCode即为列表的哈希码值,返回即可。

    (五)迭代器相关

    (1)

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

     返回一个在列表元素之上的迭代器

    此方法是实现了了List接口的iterator()方法,内部是通过创建一个Itr实例并返回来实现的

    AbstractList定义的modCount成员变量如下,它主要记录列表实例创建之后,发生结构性修改的次数。用于判断列表是否在创建完迭代器之后,发生并发修改的异常。

    protected transient int modCount = 0;

    Itr是实现Iterator接口的内部类,它的定义依赖于列表的size()、get(int)、remove(int)方法,其具体定义如下:

        private class Itr implements Iterator<E> {
    
            int cursor = 0;    //下一次调用next()方法返回元素的索引
            int lastRet = -1;  //最近一次调用next()方法返回元素的索引;如果发生一次remove()操作,则被重置为-1
            int expectedModCount = modCount;  //用于检测是否发生并发修改
        
         //判断迭代器中是否还有元素,如果cursor等于列表size,则表示没有 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) {  //如果中间抛出IndexOutOfBoundsException,
              //要么就是发生并发修改(列表的remove()方法删除了该元素),此时抛出ConcurrentModificationException
              //要么就是因为迭代器自己的remove()方法删除了该元素,此时抛出NoSuchElementException checkForComodification(); throw new NoSuchElementException(); } }      
         //依赖列表的remove()方法,如果列表没有实现该方法,那么调用迭代器的这个方法将抛出UnsupportedOperationException public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1;     //调用一次此方法,就将lastRet重置为-1 expectedModCount = modCount;  //迭代过程中,通过迭代器的remove方法删除列表元素时,不会抛出并发修改异常 } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } }
         //判断在迭代器生成之后,列表是否发生(不是通过迭代器做到的)结构性修改 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }

    (2)

        public ListIterator<E> listIterator() {
            return listIterator(0);
        }

     此方法返回了一个在列表元素之上的列表迭代器。

    内部通过调用ListIterator(int)方法实现。

    (3)

        public ListIterator<E> listIterator(final int index) {
            rangeCheckForAdd(index);
            return new ListItr(index);
        }

    此方法返回一个在列表元素之上的列表迭代器。

    先是检查指定位置是否合法,非法则抛出异常;合法则创建一个ListItr的实例并返回。

    ListItr是继承Itr类,实现ListIterator接口的一个内部类,其定义如下:

        private class ListItr extends Itr implements ListIterator<E> {
            ListItr(int index) {
                cursor = index;
            }
    
         //判断列表迭代器中前面是否还有元素 public boolean hasPrevious() { return cursor != 0; }      //返回列表迭代器中前面一个元素(即,当前位置cursor减1的位置处的元素) 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; }      //更新最近一次返回的元素(即,lastRet索引指向的元素) 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(); } }      //添加指定元素到列表迭代器的当前位置处,同样也是利用列表的add(E)方法实现 public void add(E e) { checkForComodification(); try { int i = cursor; AbstractList.this.add(i, e); lastRet = -1;    //将lastRet重置为-1 cursor = i + 1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }

    (六)子列表相关

        public List<E> subList(int fromIndex, int toIndex) {
            return (this instanceof RandomAccess ?
                    new RandomAccessSubList<>(this, fromIndex, toIndex) :
                    new SubList<>(this, fromIndex, toIndex));
        }

    此方法返回一个类型为AbstractList子类的列表。返回的列表基于原列表,如果原列表实现了RandomAccess接口,那么则返回一个既继承AbstractList抽象类又实现RandomAccess接口的子类的实例;否则,返回一个只继承AbstractList抽象类的实例。

    如果(fromIndex < 0 || toIndex > size),抛出

    如果fromIndex > toIndex,抛出IllegalArgumentExceptionIndexOutOfBoundsException

    RandomAccessSubList类继承自SubList,并实现了RandomAccess接口(RandomAccess接口只是表示此类的实例支持随机访问)

    class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
        RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
            super(list, fromIndex, toIndex);    //通过调用父类SubList的构造方法创建一个子列表实例
        }
       //返回一个子列表
        public List<E> subList(int fromIndex, int toIndex) {
            return new RandomAccessSubList<>(this, fromIndex, toIndex);
        }
    }

    SubList类继承自AbstractList抽象类,因此它的实例列表可以使用AbstractList的各种已经实现的方法。

    可以看到SubList类的各种方法如set()、add()、removeRange()等的内部实现都是通过调用原列表的相应方法来实现的。另外,很多方法在执行前都会检测原列表、子列表的modCount是否相同,如果不同,则抛出并发修改异常。

    listIterator()方法则对ListIterator对原列表的一个列表迭代器进行包装,然后返回。

    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; //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();//判断是否发生过并发结构性修改(通过原列表或其的迭代器发生的remove()操作,而不是此子列表)
            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;   //保持modCount与原列表相同(上面调用了原列表的add()方法,原列表的modCount加了1)
            size++;
        }
    
        public E remove(int index) {
            rangeCheck(index);
            checkForComodification();
            E result = l.remove(index+offset);
            this.modCount = l.modCount;
            size--;  //这里更新的是子列表的size,原列表的size在上面l.remove()方法的执行过程中就已经更新完毕
            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();
        }
    }
  • 相关阅读:
    浙江省CIO协会钱塘江论坛近日在网易云创沙龙宣布成立
    用Python解析XMind
    Flask写web时cookie的处理
    一篇文章看懂Facebook和新浪微博的智能FEED
    改进网易云音乐的“音乐社交”构想
    移动端爬虫工具与方法介绍
    用供应链管理思路降低教培产品成本
    【网易严选】iOS持续集成打包(Jenkins+fastlane+nginx)
    网易严选的wkwebview测试之路
    linux多进程之间的文件锁
  • 原文地址:https://www.cnblogs.com/JeremyChan/p/11141232.html
Copyright © 2011-2022 走看看