简体   繁体   中英

Passing List<String> to String… parameter

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

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()]));

You can do the following :

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

this will convert the list to array

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()])); 
}

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)

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).

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()]));

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