Converting 'ArrayList<String> to 'String[]' in Java

2021-6-3 anglehua

How might I convert an ArrayList<String> object to a String[] array in Java?

List<String> list = ..;
String[] array = list.toArray(new String[0]);

For example:

List<String> list = new ArrayList<String>();
//add some stuff
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.

An alternative in Java 8:

String[] strings =[]::new);

Java 11+:

String[] strings = list.toArray(String[]::new);


Powered by emlog 京ICP备15036472号-3 sitemap