概述
此类提供 List
接口的骨干实现,以最大限度地减少实现“随机访问”数据存储(如数组)支持的该接口所需的工作。对于连续的访问数据(如链表),应优先使用 AbstractSequentialList
,而不是此类。
定义
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>
构造函数
protected AbstractList() { }
iterator()
public Iterator<E> iterator() { return new Itr(); }
上面用到了Ite
一个内部类 private class Itr implements Iterator<E> { 调用next时,返回元素的下标 int cursor = 0; 最近访问元素下标(next或previo),如果元素被删返回-1 int lastRet = -1; 期望改变数,当迭代时检测在此期间元数组是否改变,fast-fail的实现基础 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(); 调用外部remove方法 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(); } }
ListIterator<E>
public ListIterator<E> listIterator() { return listIterator(0); }
上面用到了 listIterator(0);
public ListIterator<E> listIterator(final int index) { rangeCheckForAdd(index); return new ListItr(index); }
ListIt
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;// cursor从Itr继承的字段,表示下一个next返回元素下标, E previous = get(i); lastRet = cursor = i; // 执行previous 标志前移 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(); } } }