Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String vararg and String array

Tags:

java

string

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 ?

like image 333
lesnar Avatar asked Mar 11 '23 12:03

lesnar


1 Answers

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.

like image 140
Bohemian Avatar answered Mar 19 '23 04:03

Bohemian