Converting Listlt;Stringgt; to String[] in Java(转换列表lt;字符串gt;Java中的字符串[])
问题描述
如何转换 列表将字符串转换为 数组?以下代码返回错误.
How do I convert a list of 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);
}
错误:
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.
这篇关于转换列表<字符串>Java中的字符串[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:转换列表<字符串>Java中的字符串[]
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01