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?
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With