基于索引的循环 (for 循环)
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
基于元素的循环 (for-each 循环)
int[] arr = {1, 2, 3, 4, 5};
for (int num : arr) {
System.out.println(num);
}
使用 `Arrays.toString()` 方法
int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));
使用 `Stream API`
int[] arr = {1, 2, 3, 4, 5};
Arrays.stream(arr).forEach(System.out::println);
使用 `Iterator`
int[] arr = {1, 2, 3, 4, 5};
Iterator
iterator = Arrays.asList(arr).iterator(); while (iterator.hasNext()) {
System.out.println(iterator.next());
}
选择哪种方法取决于你的具体需求,例如是否需要修改数组元素、是否需要并行处理等。通常情况下,基于元素的循环(for-each 循环)是最简洁和常用的方法