Passing List<String> to String… parameter

别说谁变了你拦得住时间么 提交于 2020-07-18 03:42:15

问题


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

回答1:


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



回答2:


You can do the following :

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

this will convert the list to array




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



回答4:


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



回答5:


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




回答6:


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)


来源:https://stackoverflow.com/questions/32223161/passing-liststring-to-string-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!