2

I need to pass arguments to a java method func(String, String...). Problem is I have all the strings I need to pass as arguments, but they are in an ArrayList container.

For Example:

for(...some condition...)
{
    //the other method returns an ArrayList with different size in each iteration
    ArrayList <String> values = someOtherMethod(); 
    func(values) //values is an ArrayList<String>, containing all the arguments
}

I get an error saying that ArrayList<String> can't be converted to String. The size of values changes, because the someOtherMethod method returns a container with different size each iteration, so I can't pass values[0], values[1], etc as arguments.

I'm guessing the func wants an X amount of String variables, but I don't know how to convert a container to an X amount of variables when the size of the container isn't constant.

4

3 回答 3

2

它有点复杂,因为func需要一个String,然后是任意数量的附加Strings

List<String> values = someOtherMethod();
if (values.isEmpty()) {
    // handle special case
} else{
    func(values.get(0), values.subList(1, values.size()).toArray(new String[]));
}
于 2013-09-28T11:02:12.530 回答
2

The "..." operator accepts arrays, so you could just do the following:

ArrayList <String> values = someOtherMethod(); 
func(values.toArray(new String[values.size()]);
于 2013-09-28T10:58:05.290 回答
1

我猜 func 需要 X 数量的 String 变量,

我猜你正在寻找Varargs。

将您的函数签名更改为接受为

public someReturnType func(String... vargs) { }

它将可变长度的 args 作为参数。

然后在方法内部,您可以像访问它们一样

  for (String currentarg: args) {

   // do something with currentarg
 } 

附带说明:仅适用于 1.5 版。

从有关 Varargs 的文档中了解更多信息

于 2013-09-28T10:59:48.987 回答