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


71

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

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);
}

错误:

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

1
对于大多数带错误的问题,您应该张贴收到的错误消息。
2010年

1
我更喜欢stackoverflow。感谢您在Google中排名第一。
Ninjaxor

Answers:


103

你要

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

请参阅此处的文档,并请注意,您也可以以填充传递的数组的方式调用此方法,而不仅仅是使用它来计算返回的类型。另请注意,也许当您打印阵列时,您更喜欢

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

因为那将打印实际的元素。


23
使用strlist.toArray(new String [strlist.size()]); 通常效率更高。
彼得·劳瑞

19
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);


}

2
我也喜欢这种toArray方法的版本,因为它重新使用了参数strarray,而不是返回新实例
James B 2010年

3

List.toArray()必须返回一个Object数组。要获取String数组,您需要使用强制转换语法:

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

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


2

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

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

您的$ API看起来很棒,也许像'sort'这样的夫妇方法可以接受比较器,这将使它更加有用。
格雷格

谢谢!随时使用bitbucket向我发送补丁或打开功能请求。
dfa

为了查看您的实现,我必须安装20M程序来“克隆”您的254.3 KB源。
索耶2010年

使用右侧的“获取源代码”按钮:这是最新修订版的链接bitbucket.org/dfa/dollar/get/tip.zip
dfa 2010年


0

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

如果您想将List转换为字符串,请使用StringUtils.join(slist,'\ n');

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.