17

I'm struggling to pass a List of Strings into a method requiring the parameter "String...".

Can anybody help me out?

// How to put names into dummyMethod?
List<String> names = getNames();

 public void dummyMethod(String... parameter) {
    mInnerList.addAll(Arrays.asList(parameter));
}
vefthym
  • 7,422
  • 6
  • 32
  • 58
RuNaWaY87
  • 689
  • 1
  • 5
  • 12

6 Answers6

21

You'll have to convert the List<String> to a String array in order to use it in the 'varargs' parameter of dummyMethod. You can use toArray with an extra array as parameter. Otherwise, the method returns an Object[] and it won't compile:

List<String> names = getNames();
dummyMethod(names.toArray(new String[names.size()]));
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
5

You can do the following :

dummyMethod(names.toArray(new String[names.size()]) 

this will convert the list to array

Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
3

Pass String array (String[]) inside method. You will have to convert your List to Array and then pass it.

if (names != null) {
    dummyMethod(names.toArray(new String[names.size()])); 
}
Naman Gala
  • 4,670
  • 1
  • 21
  • 55
2

This is vararg parameter and for this you should pass array. ArrayList won't work. You can rather convert this list to array before passing to the method.

String a = new String[names.size];
list.toArray(a)
SacJn
  • 777
  • 1
  • 6
  • 16
2

Since you later parse the parameter as a List, I suggest changing the method to:

public void dummyMethod(List<String> parameter) {
    mInnerList.addAll(parameter);
}

to avoid the extra costs.

However, if you want to use this method "as it is", then you should call it like that:

dummyMethod(names.toArray(new String[names.size()]));

as Glorfindel suggests in his answer, since the three dots mean that you can call the method using many Strings, or an array of Strings (see this post for more details).

Community
  • 1
  • 1
vefthym
  • 7,422
  • 6
  • 32
  • 58
  • 1
    `toArray()` will return an `Object[]` - this won't compile. – Glorfindel Aug 26 '15 at 09:52
  • Thanks. toArray() (and some extra casting) did it! The method with "String..." parameter is part of a library, so I was trying to avoid changing it. But that would have been my next attempt to solve it. – RuNaWaY87 Aug 26 '15 at 09:53
  • @Glorfindel I was updating my answer when you commented, after seeing your answer. – vefthym Aug 26 '15 at 09:54
2

The var-arg actually accepts an array and you can use it like:

dummyMethod(names.toArray(new String[names.size()]));

Here is a sample code:

List<String> names = new ArrayList<>();
names.add("A");
names.add("B");
dummyMethod(names.toArray(new String[names.size()]));
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95