Converting 'ArrayList<String> to 'String[]' in Java
我该如何将一个ArrayList<String>
对象转换为Java中的String[]
数组?
List<String> list = ..;
String[] array = list.toArray(new String[0]);
For example:
List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
The toArray()
method without passing any argument returns Object[]
. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.
Important update : Originally the code above used new String[list.size()]
. However, this blogpost reveals that due to JVM optimizations, using new String[0]
is better now.
Java 8中的另一种选择:
String[] strings = list.stream().toArray(String[]::new);
ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray = Arrays.copyOf(objectList,objectList.length,String[].class);
使用copyOf,ArrayList也可以完成数组。
链接地址: http://www.djcxy.com/p/3364.html