java如何遍历数组
遍历数组的方法
在Java中,遍历数组有多种方式,以下是几种常见的方法:
使用for循环遍历数组

int[] array = {1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
使用增强for循环(for-each循环)遍历数组
int[] array = {1, 2, 3, 4, 5};
for (int element : array) {
System.out.println(element);
}
使用while循环遍历数组

int[] array = {1, 2, 3, 4, 5};
int i = 0;
while (i < array.length) {
System.out.println(array[i]);
i++;
}
使用Arrays.stream()方法遍历数组(Java 8及以上版本)
int[] array = {1, 2, 3, 4, 5};
Arrays.stream(array).forEach(System.out::println);
使用迭代器遍历数组(需先将数组转换为列表)
int[] array = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(array);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
注意事项
- 使用for循环时需注意数组越界问题,确保索引不超过
array.length - 1。 - 增强for循环简洁易读,但无法直接访问数组索引。
Arrays.stream()方法适用于Java 8及以上版本,支持函数式编程风格。- 将数组转换为列表时,原始数组为基本类型(如
int[])需使用包装类(如Integer[])。






