遍历数组和映射可以使用循环结构来实现。下面是一些示例代码:
遍历数组:
int[] numbers = {1, 2, 3, 4, 5};
// 使用for循环遍历数组
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// 使用for-each循环遍历数组
for (int number : numbers) {
System.out.println(number);
}
遍历映射(Map):
Map scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 80);
scores.put("Charlie", 70);
// 使用for-each循环遍历映射的键
for (String key : scores.keySet()) {
System.out.println(key + ": " + scores.get(key));
}
// 使用for-each循环遍历映射的键值对
for (Map.Entry entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
这些示例代码演示了如何使用循环结构遍历数组和映射,并输出它们的元素或键值对。
上一篇:遍历数组和相关元素
下一篇:遍历数组后将值传递到字符串中