Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert `ArrayList<String>` into a type that can be passed into a `String…` parameter

I have a function that returns an ArrayList<String>, and I need to be able to pass the result of this function into another function with a String... parameter. The problem is, the function that takes in the String... has another string already being passed in, as showed in the example below.

public void printStrings(String... strings) {
    for (String str : strings) {
        System.out.println(str);
    }

}

public ArrayList<String> getArrayList() {
    ArrayList<String> list = new ArrayList<>();

    list.add("Hello");
    list.add("World");

    return list;
}

public static void main(String[] args) {
    // This is what needs to happen, but does not work
    printStrings("Additional String", getArrayList());
    //            ^ String already being passed in

}

This additional string should not be removed, and in the actual code the function that takes in the strings would have a lot of other strings going into it, and this function should not be changed.

Note that this is not converting an ArrayList to an String[]. That would not fix this problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There isn’t a language construct that supports this exactly. You could store the List in a variable, add the additional String to the front, then convert to an array.

var list = getArrayList();
list.add(0, "Additional String");
printStrings(list.toArray(String[]::new));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading