转换列表< String> Java中的String [] [英] Converting List<String> to String[] in Java

查看:75
本文介绍了转换列表< String> Java中的String []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I convert a list 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);
}

错误:

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


推荐答案

你想要

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

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

See here for 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.

这篇关于转换列表&lt; String&gt; Java中的String []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆