AbstractList抽象类

第1部分 AbstractList介绍

AbstractList简介
AbstractList继承AbstractCollection,实现List接口,因此除了具有集合的方法属性外,还具有固定顺序,以及索引特征。
AbstractList源码中包含了四个类Itr ,ListItr,SubList,RandomAccessSubList,分别来支持迭代和获取子列表。

AbstractList构造函数

修饰语和返回类型 方法 描述
protected AbstractList()

AbstractList常用API

修饰语和返回类型 特殊方法 描述
List<E> subList(int fromIndex, int toIndex) 获取子列表
protected void removeRange(int fromIndex, int toIndex) 移除[fromIndex,toIndex)里的元素
private void rangeCheckForAdd(int index) 检查添加的index索引是否在范围[0,size]内
private String outOfBoundsMsg(int index) 返回越界信息
抽象方法
E get(int index) 获取index所在位置元素

第2部分 AbstractList数据结构

AbstractList的继承关系

java.lang.Object
   ↳     java.util.AbstractCollection<E>
         ↳   

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

AbstractList的关系图
在这里插入图片描述
图1 AbstractList的关系图

看到这个关系,我也是有点惊了,买一送四,里面定义了四个类,总共五个类。遇到这种情况,逐个击破就行了,先从被依赖的类开始,父类到子类的顺序开始分析。此外,modCount记录的时修改次数(针对增删改操作),用于fast-fail机制。

第3部分 AbstractList源码解析(基于JDK-8u201)

内部迭代器Itr

private class Itr implements Iterator<E> {
	  //下一元素指针,用来标记遍历到了哪里
      int cursor = 0;
	  //上次返回元素指针,记录上次返回了哪个元素
      int lastRet = -1;
	  //期待更改次数,用作fast-fail机制
      int expectedModCount = modCount;

      public boolean hasNext() {
      	  //下一元素指针没到最末,表示还有元素
          return cursor != size();
      }

      public E next() {
      	  //fast-fail机制,检查expectedModCount是否等于modCount,不等于则抛异常
          checkForComodification();
          try {
              int i = cursor;
              //获取下一元素
              E next = get(i);
              //修改上次返回元素的值
              lastRet = i;
              //下一元素指针后移
              cursor = i + 1;
              return next;
          } catch (IndexOutOfBoundsException e) {
              checkForComodification();
              throw new NoSuchElementException();
          }
      }
	  //移除上次调用next()时返回的元素,也就是上次返回元素
      public void remove() {
          if (lastRet < 0)
              throw new IllegalStateException();
          checkForComodification();

          try {
          	  //调用AbstractList实例对象的remove(index),注意该方法会修改modCount
              AbstractList.this.remove(lastRet);
              //移除的时候,后面的元素会往前移动,因此cursor也要前移
              if (lastRet < cursor)
                  cursor--;
              lastRet = -1;
              //调用remove的时候modCount+1了,因此要修改expectedModCount,
              //否则,后面checkForComodification都会报错
              expectedModCount = modCount;
          } catch (IndexOutOfBoundsException e) {
              throw new ConcurrentModificationException();
          }
      }

      final void checkForComodification() {
          if (modCount != expectedModCount)
			  //并发修改异常,这个异常在fast-fail中很常见,也就是在不支持并发的类中很常见
              throw new ConcurrentModificationException();
      }
  }

Itr 相比于迭代器接口,也就是多了cursor , lastRet , expectedModCount 三个成员来作为标记,其他跟普通迭代器接口没多大区别。

内部迭代器ListItr

//以下方法都继承ListIterator的方法
private class ListItr extends Itr implements ListIterator<E> {
	  //构造函数,可指定起始遍历下表
      ListItr(int index) {
          cursor = index;
      }
	  //向前遍历
      public boolean hasPrevious() {
          //下一元素指针不为0,说明前面还有元素
          return cursor != 0;
      }
	  //获取上一个元素,原理和Itr获取下一个元素一样
      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;
      }
	  //修改上次返回的元素为e
      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;
              //添加到下一元素位置,会将i及后面的元素都后移,因此下一元素(i的位置)也被后移了
              AbstractList.this.add(i, e);
              lastRet = -1;
              cursor = i + 1;
              expectedModCount = modCount;
          } catch (IndexOutOfBoundsException ex) {
              throw new ConcurrentModificationException();
          }
      }
  }

ListItr 相比于其父类Itr ,多实现了向前遍历,以及增加修改元素的功能,这些方法都是在ListIterator接口中定义的。从这两个迭代器中,我们看到获取迭代顺序的方式,是通过get(index)方式来获取的。后面会分析为什么用这个方式。

子类 SubList

class SubList<E> extends AbstractList<E> {
	//列表
    private final AbstractList<E> l;
    //偏移量
    private final int offset;
    //容量
    private int size;
	//将[fromIndex,toIndex)元素作为子列表,注意左闭右开
    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();
        //用偏移量取设置,调用的是AbstractList的set方法,后面的函数也是
        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) {
    	//从size开始,将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() {
    	//调用AbstractList的listIterator方法
        return listIterator();
    }

    public ListIterator<E> listIterator(final int index) {
        checkForComodification();
        rangeCheckForAdd(index);
		//匿名内部类的用法,需要重写ListIterator的所有抽象方法
        return new ListIterator<E>() {
        	//通过AbstractList创建迭代的的方法创建
            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();
    }
}

从这个类的方法上可以看出,除了多了个具体的偏移量,其他都是调用了父类AbstractList的方法,而AbstractList中必定存在抽象方法,也就是说,SubList只能在AbstractList的具体子类实例中,才能真正使用咯。

外部类 RandomAccessSubList

//RandomAccess 接口,支持随机访问,而数组本身就可以通过下标随机访问
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);
    }
}

RandomAccessSubList相比SubList也就多实现了个随机访问的接口,并且没有提供更多的方法实现。

AbstractList

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

    protected AbstractList() {
    }
	//添加元素到最末尾,也就是size的位置
    public boolean add(E e) {
        add(size(), e);
        return true;
    }
	
    abstract public E get(int index);
	
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }

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

    public E remove(int index) {
        throw new UnsupportedOperationException();
    }
	
    public int indexOf(Object o) {
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)//下一元素相等,此时cursor已经后移,因此返回previousIndex
                    return it.previousIndex();
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }
	//从后往前遍历,原理跟indexOf相同,只是方向相反。
    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;
    }

    public void clear() {
    	//清除整个范围
        removeRange(0, size());
    }
	//从index开始,将集合添加进去,默认是按个添加
    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;
    }
	//获取迭代器
    public Iterator<E> iterator() {
        return new Itr();
    }
	//获取列表迭代器,多了向前的功能
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }
	//获取列表迭代器,指定起始遍历下标
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);
        return new ListItr(index);
    }
   	//获取子列表,根据类是否实现了RandomAccess接口,决定返回哪种列表,是策略模式的雏形
    public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<>(this, fromIndex, toIndex) :
                new SubList<>(this, fromIndex, toIndex));
    }
	//判断o是否跟列表实例相等
    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());
    }
	//获取哈希码,继承自Object的方法
    public int hashCode() {
        int hashCode = 1;
        //31^(n)+a1*31^(n-1)+a2*31^(n-2)+....+an
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }

    protected void removeRange(int fromIndex, int toIndex) {
    	//获取fromIndex位置起始的迭代器
        ListIterator<E> it = listIterator(fromIndex);
        //遍历并移除
        for (int i=0, n=toIndex-fromIndex; i<n; i++) {
            it.next();
            it.remove();
        }
    }
    
    protected transient int modCount = 0;
	//检查能否在index位置插入元素,最多在首尾,也就是[0,size]范围
    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();
    }
}

对于这种动不动好几百行的代码,一次性看下来很容易烦躁,自然内部类之类,能分出来就分出来咯。不过随着代码阅读量增加,就不会觉得这代码长了,只是划分出来,会觉得更有层次感,也更能理清每一个成员关系。

前文提到,迭代过程使用了get(index)的方式,但是AbstractList中,该方法是抽象方法。至于为什么这么做,因为List只规定了内部元素有序,但是并不规定所有实现都能随机访问。也就是说,可以通过数组和链表两种方式实现,而这两种数据结构获取元素的方式是不同的,因此,只能定义为抽象方法。

AbstractList抽象类的代码逻辑并不复杂,只是多了两个subList,其他跟AbstractCollection差不多,就是多了索引,也就是Index相关的操作,这个跟我们之前分析接口得出的结论一样。那么从这个类中,主要就是学习怎么把复杂成员抽出来了。

发布了17 篇原创文章 · 获赞 0 · 访问量 361

猜你喜欢

转载自blog.csdn.net/kubiderenya/article/details/105334064