Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I create a new Java array inline? [duplicate]

Tags:

java

arrays

Why does the first one work and the second not work?

1) OK

String[] foo = {"foo"};
bar.setArray(foo);

2) BAD

bar.setArray({"foo"});

Is there a quick way to create a String[] on a single line?

like image 304
Trevor Allred Avatar asked Nov 27 '22 23:11

Trevor Allred


2 Answers

bar.setArray(new String[] { "foo" });

I believe this format is required because Java does not want to imply the array type. With the array initialization format, the type is defined explicitly by the assigned variable's type. Inline, the array type cannot be inferred.

like image 173
iammichael Avatar answered Dec 16 '22 11:12

iammichael


As others have said:

bar.setArray(new String[] {"foo"});

It was planned to allow getting rid of the new String[] in J2SE 5.0, but instead we have varargs. With varargs, you can slightly change the the declaration of setArray to use ... in place of [], and ditch the new String[] { }.

public final class Bar {
    public void setArray(String... array) {
    [...]
}

[...]
    bar.setArray("foo"); 
like image 28
Tom Hawtin - tackline Avatar answered Dec 16 '22 11:12

Tom Hawtin - tackline