5

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?

Trevor Allred
  • 888
  • 2
  • 13
  • 22

4 Answers4

33
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.

iammichael
  • 9,477
  • 3
  • 32
  • 42
6

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"); 
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
2

You should use this:

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

Andrey Adamovich
  • 20,285
  • 14
  • 94
  • 132
0

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

  • Here's just a link to reiterate the comment of Kev: http://stackoverflow.com/questions/1154008/java-anyway-to-declare-an-array-in-line/7300558#7300558 (yes, I was about to flag you; with 6 flags you would've been kicked out). – BalusC Sep 05 '11 at 02:29