Array of Strings and Varargs Strings

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

The first method takes an array of strings, where, since the second method takes one or more String arguments. What are the various features that they provide?

Also, I don't know why, but this works:

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 
    }
}
0
source share
3 answers

There is no difference only if it has other elements.

For instance:

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

perhaps, since there is no way jvm will think it useris still an element args.

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

will cause problems.

+4
source

, , varargs "," .

:

varargs .

.

: Java public void method(String ... args, String user) varargs , .

+2

, : , ,

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

}

0

Source: https://habr.com/ru/post/1663931/


All Articles