An array of Strings vs String Varargs

限于喜欢 提交于 2019-12-06 15:13:36

问题


What is the difference between void method(String[] a) and void method(String... a)?

The first method take an array of Strings where as the second method takes one or more String arguments. What are the different features that they provide?

Moreover, don't know why but this is working:

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 
    }
}

回答1:


There is no difference, only if there are other elements after it in the signature.

For instance:

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

is possible, since there is no way the jvm will think user is still an element of args.

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

will cause trouble, though.




回答2:


The only difference is when you invoke the method, and the possible ways to invoke it as varargs allow multiple strings separated by "," or the use of an array as a parameter.

Important Note:

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

Documentation.

Edit: Java doesn't allow this public void method(String ... args, String user) as varargs must be the last parameter to be called.




回答3:


Not nice, but sometimes very usefull: If at time of writing your code you do not know which args your method gets as input your code would look like

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);        
    }        
}

}



来源:https://stackoverflow.com/questions/35455230/an-array-of-strings-vs-string-varargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!