更好的问题可能是:Why wouldn't you want to use a FOR loop to iterate through an array? 有很多方法可以遍历数组或集合,并且没有法律规定您必须使用 FOR 循环。在很多情况下,它只是速度、易用性和可读性的最佳选择。然而,在其他情况下却不是:
数组:
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
使用典型的 for 循环显示数组:
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
使用增强的for循环显示数组:
for(Integer num : array) {
System.out.println(num);
}
使用 do/while 循环显示数组:
int i = 0;
do {
System.out.println(array[i++]);
} while (i < array.length);
使用 while 循环显示数组:
int j = 0;
while (j < array.length) {
System.out.println(array[j++]);
}
通过递归迭代显示数组:
iterateArray(array, 0); // 0 is the start index.
// The 'iterateArray()' method:
private static int iterateArray(int[] array, int index) {
System.out.println(array[index]);
index++;
if (index == array.length) {
return 0;
}
return iterateArray(array,index);
}
使用 Arrays.stream() (Java8+) 显示数组:
Arrays.stream(array).forEach(e->System.out.print(e + System.lineSeparator()));
使用 IntStream (Java8+) 显示数组:
IntStream.range(0, array.length).mapToObj(index -> array[index]).forEach(System.out::println);
选择你想要的武器......