Java——增强for循环

一、介绍

增强for循环(foreach),专门用来遍历集合或者数组,底层实现使用迭代器。

二、定义格式

for(变量类型 变量 : 数组/集合){
   // 处理数据
}

变量就是每次循环所获取的元素,变量类型就是数组或者集合的元素类型

IDEA快速构建增强for循环:集合/数组.for

例子

Collection<String> coll = new ArrayList<>();
coll.add("Java");
coll.add("PHP");
coll.add("C#");
coll.add("GO");
for (String s : coll) {
    System.out.println(s);
}
// Java
// PHP
// C#
// GO

三、注意

当对数组中的元素进行修改、删除、新增时,请使用普通for循环。

原文地址:https://www.cnblogs.com/xulinjun/p/14770583.html