繁体   English   中英

在Java中将包含字符串的ArrayList转换为字符串数组的另一种方法?

[英]Another way to convert ArrayList containing Strings to an array of Strings in Java?

我已经检查了以下stackoverflow源以解决我的问题:

StackOverflow链接

但是,在应用最佳解决方案时,仍然出现错误,如下所示:

我的清单在这里定义:

List linhaInicial = new ArrayList();

我的转换是在这里进行的:

String[] convertido = linhaInicial.toArray(new String[linhaInicial.size()]);

问题是我仍然收到以下错误:

Error:(86, 59) java: incompatible types
required: java.lang.String[]
found:    java.lang.Object[]

我的转换仍然以某种方式仍返回Object[] ,而现在应该返回String[]

有什么办法吗?

谢谢!

不要使用原始类型

List linhaInicial = new ArrayList();

应该

List<String> linhaInicial = new ArrayList<>();

变更:

List linhaInicial = new ArrayList(); // can contain any Object. 
             //So compiler throws an error while converting an Object to String.

List<String> linhaInicial = new ArrayList<String>(); // using Generics ensures
                          //that your List can contain only Strings, so, compiler
                            //will not throw "incompatible types" error

始终尝试在声明中包括list元素的类型:

List<String> linhaInicial = new ArrayList<String>();

尽可能避免使用原始类型。

你必须改变

List linhaInicial = new ArrayList(); // you are using raw type List

List<String> linhaInicial = new ArrayList();// you have to use String type List

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM