Java集合Iterator迭代器的实现
一、迭代器概述
1、什么是迭代器?
在Java中,有很多的数据容器,对于这些的操作有很多的共性。Java采用了迭代器来为各种容器提供了公共的操作接口。这样使得对容器的遍历操作与其具体的底层实现相隔离,达到解耦的效果。
在Iterator接口中定义了三个方法:

2、迭代器使用
public static void main(String[] args)
{
List<String> list=new ArrayList<>();
list.add("abc");
list.add("edf");
list.add("ghi");
for(Iterator<String> it=list.iterator();it.hasNext();)
{
System.out.println(it.next());
}
}
执行结果: 
二、ArrayList的Iterator实现
private class Itr implements Iterator<E>
{
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
...
}
在ArrayList内部定义了一个内部类Itr,该类实现了Iterator接口。
在Itr中,有三个变量分别是
cursor:表示下一个元素的索引位置
lastRet:表示上一个元素的索引位置
expectModCount:预期被修改的次数
下面看一下Itr类实现了Iterator接口的三个方法:
public boolean hasNext()
{
return cursor != size;//当cursor不等于size时,表示仍有索引元素
}
public E next() //返回下一个元素
{
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
在next()方法中有一个checkForComodification()方法,其实现为:
final void checkForComodification()
{
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
可以看到,该函数是用来判断集合的修改次数是否合法。
在集合内部维护一个字段modCount用于记录集合被修改的次数,每当集合内部结构发生变化(add,remove,set)时,modCount+1。
在迭代器内部也维护一个字段expectedModCount,同样记录当前集合修改的次数,初始化为集合的modCount值。当我们在调用Iterator进行遍历操作时,如果有其他线程修改list会出现modCount!=expectedModCount的情况,就会报并发修改异常java.util.ConcurrentModificationException。下面为示例代码:
public static void main(String[] args)
{
ArrayList<String> aList=new ArrayList<String>();
aList.add("bbc");
aList.add("abc");
aList.add("ysc");
aList.add("saa");
System.out.println("移除前:"+aList); Iterator<String> it=aList.iterator();
while(it.hasNext())
{
if("abc".equals(it.next()))
{
aList.remove("abc");
}
}
System.out.println("移除后:"+aList);
}

上面的代码中,如果我们只使用迭代器来进行删除,则不会出现并发修改异常错误。
public static void main(String[] args)
{
ArrayList<String> aList=new ArrayList<String>();
aList.add("bbc");
aList.add("abc");
aList.add("ysc");
aList.add("saa");
System.out.println("移除前:"+aList); Iterator<String> it=aList.iterator();
while(it.hasNext())
{
if("abc".equals(it.next()))
{
it.remove();
}
}
System.out.println("移除后:"+aList);
}

public void remove()
{
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
在执行remove操作时,同样先执行checkForComodification(),然后会执行ArrayList的remove()方法,该方法会将modCount值加1,这里我们将expectedModCount=modCount,使之保持统一。
三、ListIterator
上面可以看到,Iterator只提供了删除元素的方法remove,如果我们想要在遍历的时候添加元素怎么办?
ListIterator接口继承了Iterator接口,它允许程序员按照任一方向遍历列表,迭代期间修改列表,并获得迭代器在列表中的当前位置。
ListIterator接口定义了下面几个方法:

下面使用ListIterator来对list进行边遍历边添加元素操作:
public static void main(String[] args)
{
ArrayList<String> aList = new ArrayList<String>();
aList.add("bbc");
aList.add("abc");
aList.add("ysc");
aList.add("saa");
System.out.println("移除前:" + aList);
ListIterator<String> listIt = aList.listIterator();
while (listIt.hasNext())
{
if ("abc".equals(listIt.next()))
{
listIt.add("haha");
}
}
System.out.println("移除后:" + aList);
}

Java集合Iterator迭代器的实现的更多相关文章
- Java集合中迭代器的常用用法
该例子展示了一个Java集合中迭代器的常用用法public class LinkedListTest { public static void main(String[] args) { List&l ...
- JAVA基础——集合Iterator迭代器的实现
一.迭代器概述 1.什么是迭代器? 在Java中,有很多的数据容器,对于这些的操作有很多的共性.Java采用了迭代器来为各种容器提供了公共的操作接口.这样使得对容器的遍历操作与其具体的底层实现相隔离, ...
- Java 集合:迭代器(Iterator, Iterable)
Iterator接口 public interface Iterator<E> { boolean hasNext(); E next(); void remove(); } 访问元素前需 ...
- java集合-Iterator迭代
我们常常使用 JDK 提供的迭代接口进行 Java 集合的迭代. Iterator iterator = list.iterator(); while(iterator.hasNext()){ Str ...
- Java之iterator迭代器和iterable接口
java.lang.Iterable java.util.Iterator Iterator是迭代器类,而Iterable是接口. 好多类都实现了Iterable接口,这样对象就可以调用iterato ...
- Java集合--Iterator和Enumeration比较
转载请注明出处:http://www.cnblogs.com/skywang12345/admin/EditPosts.aspx?postid=3311275 第1部分 Iterator和Enumer ...
- JAVA集合--Iterator接口
本文首发于cartoon的博客 转载请注明出处:https://cartoonyu.github.io/cartoon-blog 上一篇文章中我在集合元素的遍历中已经有涉及到I ...
- 集合——iterator迭代器
Iterator接口: Iterator接口使用: 其中,集合Collection接口的定义也是使用多态,必须要创建它的子类对象才行,子类接口也是不能直接创建对象的(List接口): 其中wihle的 ...
- 【Java】Iterator迭代器总结
迭代器是一个对象,它的工作时遍历并选择序列中的对象,而客户端程序员不必知道或关心该序列底层的结构,此外,迭代器通常被称为轻量级对象:创建它的代价小.因此,经常可以见到对迭代器有些奇怪的限制,例如Jav ...
随机推荐
- 支付宝支付后回调通知中responseTxt=true isSign=False可能的问题
在做支付宝的二维码扫码支付功能,生成二维码成功,扫描后也能付款,付款后也能回调通知到我的页面,但是验证签名的时候出错,找了好久终于找到是什么原因: 引用 1. 用的RSA签名验证,默认密钥纯字符,并不 ...
- 频域分辨率与DFT,DCT,MDCT理解
搞了这么久音频算法,有些细节还没有很清楚. 比如DFT和DCT有哪些区别,DFT系数为什么会是对称的,同样帧长的数据,各自的频域分辨率是多少? 今天决定搞清楚这些问题, 首先DFT的系数对称(2N点的 ...
- 安装 LuaSocket
如果你安装有 Lua 模块的安装和部署工具 -- LuaRocks,那么一条指令就能安装部署好 LuaSocket: luarocks install luasocket
- 1.C#中几个简单的内置Attribute
阅读目录 一:Obsolete 二:Conditional 一:Obsolete 这个内置属性是说这个方法废弃了不可用,它有两个参数,第一个参数message是说废弃的原因,第二个参数err ...
- android google 统计导致的文件冲突
android studio 加入google 统计 1. buildscript { repositories { jcenter() } dependencies { classpath 'com ...
- 一台服务器部署多个tomcat
bin 目录下两文件 catalina.sh.startup.sh conf 目录下一个文件 server.xml
- windows下Android利用ant自动编译、修改配置文件、批量多渠道,打包生成apk文件
原创文章,转载请注明:http://www.cnblogs.com/ycxyyzw/p/4535459.html android 程序打包成apk,如果在是命令行方式,一般都要经过如下步骤: 1.用a ...
- thinking in object pool
1.背景 对象池为了避免频繁创建耗时或耗资源的大对象,事先在对象池中创建好一定数量的大对象,然后尽量复用对象池中的对象,用户用完大对象之后放回对象池. 2.问题 目前纵观主流语言的实现方式无外乎3个步 ...
- OceanBase RPC机制简要说明
http://note.youdao.com/share/?id=d2163a7ba8ec1ec58e64683a961c5121&type=note RPC是OB一个比较重要的各个组件间进行 ...
- Zynq学习笔记(1)
做硬件的第一个实例,一般当然是LED点灯啦~ 硬件:ZedBoard 软件:ISE 14.7 1.新建工程 2.选择平台 3.新建完成后,输入如下代码: `timescale 1ns / 1ps // ...