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
- Iterator
- Iterator
- Iterator
- iterator
- Iterator
- Iterator
- iterator
- iterator
- Iterator
- iterator
- iterator
- iterator
- Iterator
- iterator
- Iterator
- iterator
- iterator
- Iterator()
- 序列化二叉树
- 总览
- 过河问题
- python解决sql注入以及特殊字符
- COLOR
- iterator
- python中单,双引号和三引号
- STM32位带操作
- java.util.concurrent并发包诸类概览
- SDUT2937---人活着系列之寻找最完美的人生
- Linux中修改mysql的默认编码
- π的计算
- poj 动态规划
- 我要追求的未来,从这一步开始