简体   繁体   English

传递清单 <String> to String ...参数

[英]Passing List<String> to String… parameter

I'm struggling to pass a List of Strings into a method requiring the parameter " String... ". 我正在努力将一个字符串List传递给一个需要参数“ 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 . 您必须将List<String>转换为String数组才能在dummyMethod的'varargs'参数中使用它。 You can use toArray with an extra array as parameter. 您可以使用带有额外数组的toArray作为参数。 Otherwise, the method returns an Object[] and it won't compile: 否则,该方法返回一个Object[] ,它将不会编译:

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. 在方法内传递String数组( String[] )。 You will have to convert your List to Array and then pass it. 您必须将List转换为Array然后传递它。

if (names != null) {
    dummyMethod(names.toArray(new String[names.size()])); 
}

This is vararg parameter and for this you should pass array. 这是vararg参数,为此您应该传递数组。 ArrayList won't work. ArrayList不起作用。 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: 由于您稍后将参数解析为List,我建议将方法更改为:

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). 正如Glorfindel在他的回答中所建议的,因为这三个点意味着你可以使用许多字符串或字符串数​​组来调用该方法(有关更多详细信息,请参阅此文章 )。

The var-arg actually accepts an array and you can use it like: var-arg实际上接受一个数组,你可以使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM