How to pass strings from ArrayList <String> to a method that accepts multiple strings?

I have an ArrayList with strings and a method that can take any number of strings as arguments.

ArrayList<String> list = new ArrayList<String>(); // Filling the list with strings... public addStrings(String... args) { // Do something with those Strings } 

Now I would like to pass these lines from my list of arrays to this method. How can i do this? How can I call addStrings() Note that the number of lines in an arraylist can vary.

+4
source share
1 answer

You can do something like this:

 ArrayList<String> list = new ArrayList<String>(); // Filling the list with strings... String[] stringArray = new String[list.size()]; list.toArray(stringArray); addStrings(stringArray); public addStrings(String... args) { // Do something with those Strings } 

Pass your lines in a primitive array. From the varargs document:

Three periods after the final parameter type indicate that the last argument can be passed as an array or as a sequence of arguments .

All you have to do is infer String[] from your List , and then pass it to the addStrings(String... args) method.

Confirm this question for a link to documentation.

+3
source

Source: https://habr.com/ru/post/1499856/


All Articles