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?
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");
Unfortunately, the closest that Java comes to inline arrays is new String[]{"foo", "bar"} however there is a neat trick that allows you to do something like
array("foo", "bar") with the type automatically inferred.
I have been working on a useful API for augmenting the Java language to allow for inline arrays and collection types. For more details google project Espresso4J or check it out here