iterator
2015-09-11 20:46
337 查看
核心变量:
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()方法返回
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(); } }
相关文章推荐
- 第55讲:Scala中Infix Type实战详解
- 总览
- codeforce--Vasya and Petya's Game
- Android开发——构建自定义组件
- golang 反射结构字段类型
- OC-字符串的运用
- Dll文件动态调用
- 很特别的一个动态规划教程
- HDU 1695 GCD
- mysql查看数据库所有外键列表指令
- Making sense of LayoutInflater
- 纹理缓存
- Asp文件锁定脚本
- MATLAB deeplearning-toolbox CNN
- hdu1081dp
- Cocos2dx 3.X jsb加载JavaScript源码文件分析
- MySQL 事件跟踪器
- Continuous Subarray Sum II
- IOS IPA打包遇到的问题:code signing is required for product type 'Application' in SDK 'iOS 8.1
- Regular Expression Matching