在Java基础 -- 持有对象(容器)已经详细介绍到,集合(Collection)的种类有不少种,好比ArrayList、LinkedList、HashSet...。html
因为集合的内部结构不一样,不少时候可能不知道该怎样去遍历一个集合中的元素。因此为了使对集合内元素的操做更为简单,Java引入了迭代器模式!
java
迭代器把访问逻辑从不一样类型的集合类型中抽取出来,从而避免向外部暴露集合的内部结构。编程
对于数组咱们使用的是下标来进行处理的:数组
1 int array[] = new int[3]; 2 for (int i = 0; i < array.length; i++) { 3 System.out.println(array[i]); 4 }
对ArrayList的处理:安全
1 List<String> list = new ArrayList<String>(); 2 for(int i = 0 ; i < list.size() ; i++){ 3 String string = list.get(i); 4 }
对于这两种方式,咱们老是都知道它的内部结构,访问代码和集合自己是紧密耦合的,没法将访问逻辑从集合类和客户端代码中分离出来。不一样的集合会对应不一样的遍历方法,客户端代码没法复用。在实际应用中如何将上面两个集合整合是至关麻烦的。因此才有Iterator,它老是用同一种逻辑来遍历集合。使得客户端自身不须要来维护集合的内部结构,全部的内部状态都由Iterator来维护。客户端不用直接和集合进行打交道,而是控制Iterator向它发送向前向后的指令,就能够遍历集合。this
迭代器一般被称为轻量级对象;建立它的代价小,所以,常常能够看到对迭代器有些奇怪的限制,例如,Java的Iterator只能单向移动,这个Iterator只能用来:spa
为了观察它的工做方式,让咱们来看一个例子:线程
import java.util.*; public class SimpleIteration { public static void main(String[] args) { //默认从小到大排序 List<Person> pers = new ArrayList<Person>(); Person p1 = new Person("吴定会",50,true); pers.add(p1); Person p2 = new Person("沈艳霞",46,false); pers.add(p2); Person p3 = new Person("张三",17,true); pers.add(p3); Person p4 = new Person("李四",34,false); pers.add(p4); Iterator<Person> it = pers.iterator(); //检查list中是否还有元素 while(it.hasNext()) { //获取list中下一个元素 Person p = it.next(); System.out.print(p + " "); } System.out.println(); it = pers.iterator(); for(int i=0;i<4;i++) { //获取list中下一个元素 it.next(); //将迭代器新近返回的元素删除 it.remove(); System.out.println(i + ":" + pers); } System.out.print(pers); } }
输出结果以下:code
吴定会-50-true 沈艳霞-46-false 张三-17-true 李四-34-false 0:[沈艳霞-46-false, 张三-17-true, 李四-34-false] 1:[张三-17-true, 李四-34-false] 2:[李四-34-false] 3:[] []
如今考虑建立一个display()方法,它没必要知晓集合的确切类型:htm
import java.util.*; public class CrossContainerIteration { public static void display(Iterator<Person> it) { while(it.hasNext()) { Person p = it.next(); System.out.print(p + " "); } System.out.println(); } public static void main(String[] args) { ArrayList<Person> pers = new ArrayList<Person>(); Person p1 = new Person("吴定会",50,true); pers.add(p1); Person p2 = new Person("沈艳霞",46,false); pers.add(p2); Person p3 = new Person("张三",17,true); pers.add(p3); Person p4 = new Person("李四",34,false); pers.add(p4); LinkedList<Person> persLL = new LinkedList<Person>(pers); HashSet<Person> persHS = new HashSet<Person>(pers); display(pers.iterator()); display(persLL.iterator()); display(persHS.iterator()); } }
输出:
吴定会-50-true 沈艳霞-46-false 张三-17-true 李四-34-false 吴定会-50-true 沈艳霞-46-false 张三-17-true 李四-34-false 张三-17-true 吴定会-50-true 沈艳霞-46-false 李四-34-false
能够看到display()方法不包含任何有关它所遍历的集合的类型信息,而这也展现了Iterator的真正威力,可以将遍历集合的操做与集合底层结构分离。正由于如此,咱们有时才会说,迭代器统一了对集合的访问方式。
ListIterator是一个更增强大的Iterator的子类型,它只能用于各类List类的访问,尽管Iterator只能向前移动,可是ListIterator能够双向移动。它还能够产生相对于迭代器在列表中指向的当前位置的前一个和后一个元素的索引,而且可使用set()方法替代它访问过的最后一个元素。能够经过调用listIterrator()方法产生一个指向List开始处的ListIterator,而且还能够经过调用listIterator(n)方法建立一个一开始指向列表索引为n的元素处的ListIterator。下面的示例演示了全部这些能力:
import java.util.*; public class ListIteration { public static void main(String[] args) { List<Person> pers = new ArrayList<Person>(); Person p1 = new Person("吴定会",50,true); pers.add(p1); Person p2 = new Person("沈艳霞",46,false); pers.add(p2); Person p3 = new Person("张三",17,true); pers.add(p3); Person p4 = new Person("李四",34,false); pers.add(p4); //从前向后遍历 ListIterator<Person> it = pers.listIterator(); while(it.hasNext()) { System.out.print(it.next() + " "); } System.out.println(); //从后向前遍历 while(it.hasPrevious()) { System.out.print(it.previous() + " "); } System.out.println(); System.out.println(pers); //建立一个开始指向第三个索引元素处的ListIterator it = pers.listIterator(3); while(it.hasNext()) { System.out.println(it.next()); //替换在列表中从位置3开始向前的全部Person对象 it.set(p1); } System.out.println(pers); } }
输出:
吴定会-50-true 沈艳霞-46-false 张三-17-true 李四-34-false 李四-34-false 张三-17-true 沈艳霞-46-false 吴定会-50-true [吴定会-50-true, 沈艳霞-46-false, 张三-17-true, 李四-34-false] 李四-34-false [吴定会-50-true, 沈艳霞-46-false, 张三-17-true, 吴定会-50-true]
在Java中Iterator为一个接口,它只提供了迭代的基本规则。在JDK中它是这样定义的:对Collection进行迭代的迭代器。迭代器取代了Java Collection Framework中的Enumeration。迭代器与枚举有两点不一样:
其接口定义以下:
package java.util; public interface Iterator<E> { boolean hasNext();//判断是否存在下一个对象元素 E next();//获取下一个元素 void remove();//移除元素 }
Java中还提供了一个Iterable接口,Iterable接口实现后的功能是返回一个迭代器,咱们经常使用的实现了该接口的子接口有:Collection<E>、List<E>、Set<E>等。该接口的iterator()方法返回一个标准的Iterator实现。实现Iterable接口容许对象成为foreach语句的目标。就能够经过foreach语句来遍历你的底层序列。
Iterable接口包含一个能产生Iterator对象的方法,而且Iterable被foreach用来在序列中移动。所以若是建立了实现Iterable接口的类,均可以将它用于foreach中。
Iterable接口的具体实现:
Package java.lang; import java.util.Iterator; public interface Iterable<T> { Iterator<T> iterator(); }
使用迭代器遍历集合:
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("张三1"); list.add("张三2"); list.add("张三3"); list.add("张三4"); List<String> linkList = new LinkedList<String>(); linkList.add("link1"); linkList.add("link2"); linkList.add("link3"); linkList.add("link4"); Set<String> set = new HashSet<String>(); set.add("set1"); set.add("set2"); set.add("set3"); set.add("set4"); //使用迭代器遍历ArrayList集合 Iterator<String> listIt = list.iterator(); while(listIt.hasNext()){ System.out.println(listIt.next()); } //使用迭代器遍历Set集合 Iterator<String> setIt = set.iterator(); while(setIt.hasNext()){ System.out.println(listIt.next()); } //使用迭代器遍历LinkedList集合 Iterator<String> linkIt = linkList.iterator(); while(linkIt.hasNext()){ System.out.println(listIt.next()); } }
使用foreach遍历集合:
List<String> list = new ArrayList<String>(); list.add("张三1"); list.add("张三2"); list.add("张三3"); list.add("张三4"); for (String string : list) { System.out.println(string); }
能够看出使用foreach遍历集合的优点在于代码更加的简洁,更不容易出错,不用关心下标的起始值和终止值。
在使用Iterator的时候禁止对所遍历的容器进行改变其大小结构的操做。例如: 在使用Iterator进行迭代时,若是对集合进行了add、remove操做就会出现ConcurrentModificationException异常。
List<String> list = new ArrayList<String>(); list.add("张三1"); list.add("张三2"); list.add("张三3"); list.add("张三4"); //使用迭代器遍历ArrayList集合 Iterator<String> listIt = list.iterator(); while(listIt.hasNext()){ Object obj = listIt.next(); if(obj.equals("张三3")){ list.remove(obj); } }
由于在你迭代以前,迭代器已经被经过list.itertor()建立出来了,若是在迭代的过程当中,又对list进行了改变其容器大小的操做,那么Java就会给出异常。由于此时Iterator对象已经没法主动同步list作出的改变,Java会认为你作出这样的操做是线程不安全的,就会给出善意的提醒(抛出ConcurrentModificationException异常)
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; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") 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]; } 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(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
经过查看源码发现原来检查并抛出异常的是checkForComodification()方法。在ArrayList中modCount是当前集合的版本号,每次修改(增、删)集合都会加1;expectedModCount是当前迭代器的版本号,在迭代器实例化时初始化为modCount。咱们看到在checkForComodification()方法中就是在验证modCount的值和expectedModCount的值是否相等,因此当你在调用了ArrayList.add()或者ArrayList.remove()时,只更新了modCount的状态,而迭代器中的expectedModCount未同步,所以才会致使再次调用Iterator.next()方法时抛出异常。可是为何使用Iterator.remove()就没有问题呢?经过源码的第32行发现,在Iterator的remove()中同步了expectedModCount的值,因此当你下次再调用next()的时候,检查不会抛出异常。
使用该机制的主要目的是为了实现ArrayList中的快速失败机制(fail-fast),在Java集合中较大一部分集合是存在快速失败机制的。
快速失败机制产生的条件:当多个线程对Collection进行操做时,若其中某一个线程经过Iterator遍历集合时,该集合的内容被其余线程所改变,则会抛出ConcurrentModificationException异常。
因此要保证在使用Iterator遍历集合的时候不出错误,就应该保证在遍历集合的过程当中不会对集合产生结构上的修改。
使用Foreach时对集合的结构进行修改会出现异常:
上面咱们说了实现了Iterable接口的类就能够经过Foreach遍历,那是由于foreach要依赖于Iterable接口返回的Iterator对象,因此从本质上来说,Foreach其实就是在使用迭代器,在使用foreach遍历时对集合的结构进行修改,和在使用Iterator遍历时对集合结构进行修改本质上是同样的。因此一样的也会抛出异常,执行快速失败机制。
foreach是JDK1.5新增长的一个循环结构,foreach的出现是为了简化咱们遍历集合的行为。
for循环与迭代器的对比:
* 效率上各有各的优点:
参考文献:
[1] Java编程思想
[2] 深刻理解Java中的迭代器(部分转载)