import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class 迭代器 { static ArrayList<String> arrayList = new ArrayList<>(); public static void main(String[] args) { // TODO 自动生成的方法存根 Collection<String> aCollection = new ArrayList<String>(); aCollection.add("hello"); aCollection.add("world"); aCollection.add("java"); Iterator<String> it = aCollection.iterator(); System.out.println(it.next()); System.out.println(it.next()); System.out.println(it.next()); arrayList.add("hello"); arrayList.add("world"); arrayList.add("java"); Iterator<String> it2 = arrayList.iterator(); System.out.println(it2.next()); System.out.println(it2.next()); System.out.println(it2.next()); System.out.println("集合遍历"); /** * 普通遍历 */ for (int i = 0; i < arrayList.size(); i++) { System.out.println(arrayList.get(i)); } System.out.println("for遍历"); /** * 增强遍历 */ for (String s : arrayList) { System.out.println(s); } System.out.println("增强for遍历"); } }
输出如下
分别是迭代器
for
foreach
hello world java hello world java 集合遍历 hello world java for遍历 hello world java 增强for遍历