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

在Java中,增强for循环(也称为foreach循环)是一种简洁、安全的遍历集合或数组的方式。它从Java 5开始引入,大大简化了迭代代码的编写,避免了传统for循环中手动管理索引或迭代器的繁琐操作。
增强for循环的语法结构如下:
for (元素类型 变量名 : 集合或数组) {
// 操作变量名
}
其中,冒号“:”左边是声明的局部变量,用于接收每次迭代的元素;右边是要遍历的集合或数组。
增强for循环适用于所有实现了Iterable接口的集合类,如ArrayList、HashSet等。
立即学习“Java免费学习笔记(深入)”;
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println(name);
}
Set<Integer> numbers = new HashSet<>(Arrays.asList(1, 2, 3));
for (int num : numbers) {
System.out.println(num);
}
由于Set无序,输出顺序可能与插入顺序不同,但增强for仍能完整遍历所有元素。
使用增强for循环时,不能在遍历过程中添加或删除集合元素,否则会抛出ConcurrentModificationException。
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String s : list) {
if ("b".equals(s)) {
list.remove(s); // 错误!会抛出异常
}
}
若需在遍历中修改集合,应使用Iterator的remove方法:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if ("b".equals(s)) {
it.remove(); // 正确方式
}
}
增强for循环最适合只读遍历场景,代码清晰且不易出错。
Map<String, Integer> 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<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
</font>
基本上就这些。增强for循环让代码更简洁,只要注意别在循环里改结构,用起来很顺手。
以上就是在Java中如何使用增强for循环遍历集合_增强for循环使用经验的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号