publicclassForEach{@TestpublicvoidlistForEach(String[] args){List<String> list =Arrays.asList("AAA","BBB","CCC");for(String s : list){System.out.println(s);}}}
foreach语法糖可用于实现了Iterable接口的类
@TestpublicvoidclassForComputer(){Computer computer =newComputer();for(String s : computer){System.out.println(s);}}privatestaticclassComputerimplementsIterable<String>{privateString[] courses ={"计算机组成原理","计算机网络","算法与数据结构"};privateInteger index =0;@OverridepublicIterator<String>iterator(){returnnewIterator<String>(){@OverridepublicbooleanhasNext(){return index != courses.length;}@OverridepublicStringnext(){return courses[index++];}};}}