开发者

what is the best way of passing unknown number of strings to a function in java

I want to pass a diffrent number of strings to a function in java, it suppose to be the strings to filter a query by, it could be 2-4 strings.

What do you think will be the best way to do that?

a) creating an overload for the same function with different number of parameters? b) create a new in开发者_如何学Gostance of an array of string and pass it to the function?

any other preffered way?

thanks


Java has supported variable argument lists since 1.5:

public void myMethod(String... values)
{
    for (String val : values)
    {
        // do something
    }
}

The rules are simple:

  • The variable argument must be the last argument in the method signature.
  • It's a single argument, so all values will be of the same type.
  • Inside the method, the vararg appears to be an array.
  • When calling the method, you can either pass individual values or an array.


Creating an overload (a) has the advantage that you'll get a compile-time error if you pass wrong number of strings.

Alternatively you can use varargs.


You can go for varargs. http://www.developer.com/java/other/article.php/3323661

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜