Label

Thứ Hai, 4 tháng 6, 2012

Pass optional params with varargs: String... names

Varargs (introduced in Java SE 5) allows you to pass 0, 1, or more params to a method's vararg param. This reduces the need for overloading methods that do the similar things. For example,

package javahowto;
 
import org.apache.commons.lang.StringUtils;
 
public class HelloWorld {
    public static void main(String[] args) {
        hello();
        hello("World");
        hello("Santa", "Bye");
         
        final String[] names = {"John", "Joe"};
        hello(names);
    }
 
    public static void hello(String... names) {
        final String defaultName = "Duke";
        String msg = "Hello, ";
        msg += ((names.length == 0) ? defaultName : StringUtils.join(names, ", "));
        System.out.println(msg);
    }
}


org.apache.commons.lang.StringUtils is in commons-lang-2.4.jar. Running this example gives the following output:
Hello, Duke
Hello, World
Hello, Santa, Bye
Hello, John, Joe
BUILD SUCCESSFUL (total time: 0 seconds)
http://javahowto.blogspot.com/2008/12/pass-optional-params-with-varargs.html

Không có nhận xét nào:

Đăng nhận xét