Roxy Roxy - 3 days ago 7
Java Question

String vararg and String array

probably this has been already asked multiple times but still my doubt is not clear:

i have a method like this:

public Object getConfig(String... names) {


and when i call it as:

case 1:
configService.getConfig("str1", "str2", "str3"); // it works


case 2:

String[] names = {"str1","str2","str3"}; // it works
configService.getConfig(names);


case3:
but when i try following it does not work

String[] names = {"str1","str2","str3"};
configService.getConfig("randomString",names);


As i understand we are passing getConfig(String,String[]) which is String ... args and i expected it to work.

I do not understand why ?

Answer

Varargs is syntactic sugar that compiles this syntax:

myMethod("foo", "bar", "baz");

void myMethod(String... args) {
    //
} 

as if it were:

myMethod(new String[] {"foo", "bar", "baz"});

void myMethod(String[] args) {
    //
} 

And because the method's parameter type is compiled as myMethod(String[] args), you can explicitly pass it an array.

However, in java there is no magic "concatenation" of elements and arrays to form a single larger array, which is what you're attempting to do.


AFAIK there's no simple way to make what you are trying to do work in one statement.

Comments