字符串数组与字符串可变参数

An array of Strings vs String Varargs

void method(String[] a)void method(String... a)有什么区别?

第一种方法采用字符串数组,而第二种方法采用一个或多个字符串参数。它们提供了哪些不同的功能?

此外,不知道为什么但这是有效的:

public class Test {

    public static void main(String[] args) {
        String[] a = {"Hello", "World"};
        Test t = new Test();
        t.method(a);
    }

    void method(String...args) {
        System.out.println("Varargs");        // prints Varargs 
    }
}

没有区别,只是签名后面有其他元素。

例如:

public void method(String[] args, String user){}

是可能的,因为 jvm 不可能认为 user 仍然是 args 的一个元素。

public void method(String ... args, String user){}

不过会惹麻烦。

唯一的区别是调用该方法的时间,以及作为可变参数调用它的可能方式允许多个字符串由“,”分隔或使用数组作为参数。

重要提示:

varargs feature automates and hides the process of multiple args passed in an array.

Documentation.

编辑: Java 不允许 public void method(String ... args, String user) 因为 varargs 必须是要调用的最后一个参数。

不太好,但有时很有用: 如果在编写代码时您不知道您的方法将哪些参数作为输入,您的代码将看起来像

public class Test {
public static void main(String[] args) {        
    Test t = new Test();
    String[] a = {"Hello", "World"};
    Integer [] b = {1,2};
    t.method(a);
    t.method(b);
    t.method('a',1,"String",2.3); 
}
void method(Object...args) {
    for (Object arg : args){
    System.out.println(arg);        
    }        
}