Java For-each 和 Iterator异同点总结
相同点
- 都可以对容器进行从头到尾的遍历
for(String s:list){
System.out.print(s);
}
Iterator it = list.iterator();
while(it.hasNext()){
System.out.print(it.next());
}
- 实现了Iterable接口的类,for-each在编译器中的实现就是Iterator
List<String> list = new ArrayList<String>();
for(String s:list){
System.out.print(s);
}
![javap反编译后后的结果,看第9、16、25行]

不同点
- For-each只能读取元素内容,无法对collection进行结构性修改(ps:结构性修改一般指改变大小,或者在迭代过程中打乱)
public class test {
static class Person {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
Person p1 = new Person();
for (int i = 0; i < 5; i++) {
Person p = new Person();
p.setId(1);
p.setName("name");
list.add(p);
}
for (Person p : list) {
System.out.println(p);
list.remove(p);//throws ConcurrentModificationException
list.add(p1);//throws ConcurrentModificationException
}
}
}
- For-each只能读取当前元素,前后元素不可见,而部分Iterator可以获取前后元素(如实现了ListIterator接口的..etc)
- For-each只能单向从头到尾遍历,Iterator可以实现双向遍历
- For-each是语法糖,有很好的阅读体验,同时避免了迭代器变量多次出现减小BUG几率;Iterator模式是设计模式之一:迭代器模式
暂时就总结了这些,有时间再补充。
初学者难免有误,还望不吝赐教,感激不尽。
参考资料:
http://www.cnblogs.com/slwenyi/p/6393366.html
http://stackoverflow.com/questions/18508786/for-each-vs-iterator-which-will-be-the-better-option