iterator

来源:互联网 发布:mt4跟单软件 编辑:程序博客网 时间:2024/05/19 06:18

核心变量:

  • cursor:指向下一个将要被访问的元素的索引号
  • lastRet:指向刚被访问的元素的索引号
  • expectedModCount:通过与ModCount比较,判断是不是进行了iterator内部remove的增删操作
核心方法:
  • hasNext():比较cursor与size()
  • next():返回下一个元素
  • remove:删除集合中的元素,并更新expectedModCount和ModCount
  • checkForCoModComodification():检测expectedModCount和ModCount是否相等
Iterable接口与Iterator接口
  • Iterable接口只有一个iterator()方法,用于返回实现了Iterator接口的类
  • Iterator接口规定了操作集合元素的方法
    • hasNext()
    • next()
    • remove()
源码:来自AbstractList<E>的Itr类,这个类尤iterator()方法返回
private class Itr implements Iterator<E> {        /**         * Index of element to be returned by subsequent call to next.         */        int cursor = 0;        /**         * Index of element returned by most recent call to next or         * previous.  Reset to -1 if this element is deleted by a call         * to remove.         */        int lastRet = -1;        /**         * The modCount value that the iterator believes that the backing         * List should have.  If this expectation is violated, the iterator         * has detected concurrent modification.         */        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();        }    }


0 0
原创粉丝点击