Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

java - 转换'ArrayList <String> Java中转换为“ String []”(Converting 'ArrayList<String> to 'String[]' in Java)

如何在Java中将ArrayList<String>对象转换为String[]数组?

  ask by Alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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[] .

(不传递任何参数的toArray()方法将返回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()] .

(重要更新 :最初,以上代码使用new String[list.size()] 。)

However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

(但是, 此博文显示由于JVM优化,现在使用new String[0]更好。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...