都可以对容器进行从头到尾的遍历 for(String s:list){ System.out.PRint(s); } Iterator it = list.iterator(); while(it.hasNext()){ System.out.print(it.next()); }实现了Iterable接口的类,for-each在编译器中的实现就是IteratorList<String> list = new ArrayList<String>();for(String s:list){ System.out.print(s);}![javap反编译后后的结果,看第9、16、25行](http://img.blog.csdn.net/20170307161748338?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvam9obl9sdw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
不同点
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模式是设计模式之一:迭代器模式