遍历数组的方式

27 阅读1分钟
遍历数组的方式有多种,以下是几种常见的方式:

1. for循环遍历数组:

```
int[] nums = {1, 2, 3, 4, 5};
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}
```

2. 增强型for循环遍历数组:

```
int[] nums = {1, 2, 3, 4, 5};
for (int num : nums) {
    System.out.println(num);
}
```

3. 使用Arrays类的toString()方法输出数组:

```
int[] nums = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(nums));
```

4. 使用Arrays类的stream()方法和forEach()方法遍历数组:

```
int[] nums = {1, 2, 3, 4, 5};
Arrays.stream(nums).forEach(System.out::println);
```

5. 使用Stream.of()方法和forEach()方法遍历数组:

```
int[] nums = {1, 2, 3, 4, 5};
Stream.of(nums).forEach(System.out::println);
```