JAVA casting list of strings to string array [duplicate]

牧云@^-^@ 提交于 2019-12-13 10:00:34

问题


I am working on creating an array of strings from a list of strings. So far, I have the following code:

ArrayList<String> layerChoices = new ArrayList<>();
for(IFeatureLayer layer : layerList){
   layerChoices.add(layer.getName());
}
String[] choices = (String[])layerChoices.toArray();

The issue being that toArray() returns an Object[] and not a String[] which is producing a class cast exception when trying to cast to a String[]. Is there a simple way to accomplish my goals other than a for loop in which I would iterate through the Object[] , cast each Object to a String, and then add each String to a String[]? Seems like a lot of work for a simple task...


回答1:


Use it like this - String [] myArray = myList.toArray(new String[myList.size()]);




回答2:


Try:

String[] choices = layerChoices.toArray(new String[layerChoices.size()]);


来源:https://stackoverflow.com/questions/31030931/java-casting-list-of-strings-to-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!