在 Java 中将 List<String> 转换为 String[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2552420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:11:14  来源:igfitidea点击:

Converting List<String> to String[] in Java

javatype-conversion

提问by Christian

How do I convert a listof String into an array? The following code returns an error.

如何将字符串列表转换为数组?以下代码返回错误。

public static void main(String[] args) {
    List<String> strlist = new ArrayList<String>();
    strlist.add("sdfs1");
    strlist.add("sdfs2");
    String[] strarray = (String[]) strlist.toArray();       
    System.out.println(strarray);
}

Error:

错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
    at test.main(test.java:10)

采纳答案by jjujuma

You want

你要

String[] strarray = strlist.toArray(new String[0]);

See herefor the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer

有关文档,请参见此处,并注意您还可以通过填充传递的数组的方式调用此方法,而不仅仅是使用它来确定要返回的类型。另请注意,也许当您打印数组时,您更喜欢

System.out.println(Arrays.toString(strarray));

since that will print the actual elements.

因为这将打印实际元素。

回答by crazyscot

List.toArray()necessarily returns an array of Object. To get an array of String, you need to use the casting syntax:

List.toArray()必然返回一个对象数组。要获取字符串数组,您需要使用转换语法:

String[] strarray = strlist.toArray(new String[0]);

See the javadoc for java.util.List for more.

有关更多信息,请参阅 java.util.List 的 javadoc。

回答by Paul

public static void main(String[] args) {
    List<String> strlist = new ArrayList<String>();
    strlist.add("sdfs1");
    strlist.add("sdfs2");

    String[] strarray = new String[strlist.size()]
    strlist.toArray(strarray );

    System.out.println(strarray);


}

回答by dfa

I've designed and implemented Dollarfor this kind of tasks:

我为此类任务设计并实现了Dollar

String[] strarray= $(strlist).toArray();

回答by Arthur

hope this can help someone out there:

希望这可以帮助那里的人:

List list = ..;

列表列表 = ..;

String [] stringArray = list.toArray(new String[list.size()]);

String [] stringArray = list.toArray(new String[list.size()]);

great answer from here: https://stackoverflow.com/a/4042464/1547266

来自这里的好答案:https: //stackoverflow.com/a/4042464/1547266

回答by phil

String[] strarray = strlist.toArray(new String[0]);

String[] strarray = strlist.toArray(new String[0]);

if u want List convert to string use StringUtils.join(slist, '\n');

如果你想列表转换为字符串使用 StringUtils.join(slist, '\n');