17370845950

在Java中如何使用增强for循环遍历集合_增强for循环使用经验
增强for循环适用于遍历集合或数组,语法为“for (类型 变量 : 集合/数组)”,可简洁遍历List、Set等Iterable对象,但遍历时不可修改集合结构,否则抛出ConcurrentModificationException,需修改时应使用Iterator;遍历Map需结合keySet()或entrySet(),适合只读场景,不适用于需索引的操作。

在Java中,增强for循环(也称为foreach循环)是一种简洁、安全的遍历集合或数组的方式。它从Java 5开始引入,大大简化了迭代代码的编写,避免了传统for循环中手动管理索引或迭代器的繁琐操作。

增强for循环的基本语法

增强for循环的语法结构如下:

for (元素类型 变量名 : 集合或数组) {
    // 操作变量名
}

其中,冒号“:”左边是声明的局部变量,用于接收每次迭代的元素;右边是要遍历的集合或数组。

遍历List和Set集合的实践

增强for循环适用于所有实现了Iterable接口的集合类,如ArrayList、HashSet等。

  • 遍历ArrayList示例:
List names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
    System.out.println(name);
}
  • 遍历HashSet示例:
Set numbers = new HashSet<>(Arrays.asList(1, 2, 3));
for (int num : numbers) {
    System.out.println(num);
}

由于Set无序,输出顺序可能与插入顺序不同,但增强for仍能完整遍历所有元素。

只能访问,不能修改集合结构

使用增强for循环时,不能在遍历过程中添加或删除集合元素,否则会抛出ConcurrentModificationException。

List list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String s : list) {
    if ("b".equals(s)) {
        list.remove(s); // 错误!会抛出异常
    }
}

若需在遍历中修改集合,应使用Iterator的remove方法:

Iterator it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    if ("b".equals(s)) {
        it.remove(); // 正确方式
    }
}

适用场景与注意事项

增强for循环最适合只读遍历场景,代码清晰且不易出错。

  • 适用于数组、List、Set、Map的values()或keySet()等返回Iterable的方法。
  • 不适用于需要获取索引的场景(此时用普通for循环更合适)。
  • 遍历Map时,通常结合keySet()或entrySet()使用:
Map map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}

for (Map.Entry entry : map.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

基本上就这些。增强for循环让代码更简洁,只要注意别在循环里改结构,用起来很顺手。