[英]Incompatible Types Error When Converting/Transferring ArrayList<String> data to String[]
I'm trying to take the values I have gathered into an ArrayList of Strings and transfer them over into an array of Strings so that I can run the data through an algorithm that accepts arrays. 我试图将收集到的值放入Strings的ArrayList中,并将其转移到Strings的数组中,以便可以通过接受数组的算法来运行数据。 I am able to do this in the main method, though this is not effective because the data must be run through multiple sorting algorithms and so I need to create the array again each time I call the algorithm.
我可以在main方法中执行此操作,尽管它无效,因为数据必须通过多种排序算法运行,因此每次调用算法时都需要再次创建数组。 I decided to write it into it's own method for efficiency.
我决定将其写入自己的效率方法中。 However, the same exact code throws an error if I place it in a separate method.
但是,如果我将其放在单独的方法中,则完全相同的代码将引发错误。
Here is the culprit: 罪魁祸首:
public static String[] transferDefs(ArrayList defs){
//Copy ArrayList values into String[] for sorting
String[] a = new String[defs.size()];
for(int i = 0; i < defs.size(); i++){
a[i] = defs.get(i); //THIS LINE CAUSES ERROR
}
return a;
} }
I have also tried using the ArrayList.toArray() method rather than a for
loop. 我也尝试过使用ArrayList.toArray()方法而不是
for
循环。 The same problem occurs. 发生相同的问题。 Any suggestions?
有什么建议么? Thanks!
谢谢!
Please try the following code: 请尝试以下代码:
public static String[] transferDefs(ArrayList<String> defs) {
// Copy ArrayList values into String[] for sorting
String[] a = new String[defs.size()];
for (int i = 0; i < defs.size(); i++) {
a[i] = defs.get(i); // THIS LINE CAUSES ERROR
}
return a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.