4

I have got an ArrayList with Strings and a method that can take in any amount 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 those strings from my array list to that method. How can I do that? How would I call addStrings() Note that the amount of strings in the arraylist can vary.

user2426316
  • 7,131
  • 20
  • 52
  • 83

1 Answers1

3

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 strings in a primitive array. From the varargs documentation:

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

All you'd need to do is derive a String[] from your List and then pass it to the addStrings(String... args) method.

Credit to this question for the documentation link.

Community
  • 1
  • 1
Surveon
  • 729
  • 5
  • 12
  • ok, but how should I implement this part `String s = String.format("%s, %s, %s", strings);` if the number of arguments is only known at runtime. – user2426316 Aug 30 '13 at 19:34
  • That was only an example of a use of what I was talking about. I'll adapt my example to match your situation. – Surveon Aug 30 '13 at 19:34