Java中用list存储数组的示例
时间: 2023-11-17 12:05:40 浏览: 64
下面是一个Java中用List存储数组的示例:
```java
import java.util.ArrayList;
import java.util.List;
public class ListArrayExample {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
List<Integer> list = new ArrayList<>();
for (int i : array) {
list.add(i);
}
System.out.println("List containing array elements: " + list);
}
}
```
在这个示例中,我们首先定义了一个整数类型的数组 `array`,然后创建了一个空的 `ArrayList`,名为 `list`。接下来,我们使用 `for` 循环遍历数组中的每个元素,并将其添加到 `list` 中。最后,我们打印出存储在 `list` 中的元素。
输出结果应该为:
```
List containing array elements: [1, 2, 3, 4, 5]
```
相关问题
Java中用list存储多个数组的示例
可以使用 `List<int[]>` 来存储多个数组,示例如下:
```java
List<int[]> arraysList = new ArrayList<>();
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] array3 = {7, 8, 9};
arraysList.add(array1);
arraysList.add(array2);
arraysList.add(array3);
// 遍历输出
for (int[] array : arraysList) {
System.out.println(Arrays.toString(array));
}
```
输出结果为:
```
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
```
JAVA中用加强遍历数组
在Java中,可以使用加强的for循环语法来遍历数组。该语法使用冒号来遍历数组,示例如下:
```java
int[] arr = {1, 2, 3, 4, 5};
// 遍历数组
for (int num : arr) {
System.out.println(num);
}
```
输出结果为:
```
1
2
3
4
5
```
在上述示例中,变量`num`会依次代表数组`arr`中的每个元素,方便我们进行处理。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)