java List转数组
时间: 2024-05-10 16:17:15 浏览: 63
Java中的List可以通过toArray()方法转换为数组。以下是示例代码:
```java
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
String[] array = list.toArray(new String[list.size()]);
```
这里将List转换为String类型的数组。需要注意的是,toArray()方法的参数是一个空数组,用来指定转换后的数组类型和长度。如果不指定长度,转换后的数组长度会和List的长度相同。在本例中,使用了一个长度为List大小的数组。
相关问题
java list转数组
可以使用Java中List接口提供的toArray方法将List转换为数组,示例代码如下:
```java
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
String[] array = list.toArray(new String[0]);
System.out.println(Arrays.toString(array));
```
输出结果为:`[apple, banana, orange]`
需要注意的是,这里传入的参数是一个指定类型和长度的数组,如果传入的是一个长度为0的数组,那么会在内部自动创建一个合适长度的数组来存储List中的元素。同时,如果List中存储的元素类型与数组中指定的类型不一致,那么会抛出ArrayStoreException异常。
Java list转数组
Java中List转数组的方法有多种,其中最常用的是使用List的toArray()方法。具体实现如下:
```
List<String> list = new ArrayList<>();
String[] array = list.toArray(new String[list.size()]);
```
其中,toArray()方法需要传入一个类型相同的数组作为参数,用于存储转换后的结果。
另外,如果List中存储的是基本数据类型,可以使用Java 8的Stream API进行转换,示例代码如下:
```
List<Integer> list = new ArrayList<>();
int[] array = list.stream().mapToInt(Integer::intValue).toArray();
```
阅读全文
相关推荐











