for循环遍历
int[] array = {1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
增强for循环(foreach循环)遍历
int[] array = {1, 2, 3, 4, 5};
for (int element : array) {
System.out.println(element);
}
使用`Arrays.asList`和迭代器遍历
Integer[] array = {1, 2, 3, 4, 5};
List
list = Arrays.asList(array); Iterator
iterator = list.iterator(); while (iterator.hasNext()) {
System.out.println(iterator.next());
}
使用Java 8的Stream API遍历
Integer[] array = {1, 2, 3, 4, 5};
Arrays.asList(array).stream().forEach(x -> System.out.println(x));
或者简写形式:
Arrays.asList(array).stream().forEach(System.out::println);
以上方法都可以用来遍历数组中的元素。选择哪种方法取决于你的个人喜好和具体需求。增强for循环通常更简洁和易读,特别是在只需要遍历整个数组而不需要索引的情况下。而Stream API提供了一种更现代和函数式的方法来处理集合