简体   繁体   中英

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. 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. 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. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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