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?

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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"); 

Comments

2

You should use this:

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

Comments

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

1 Comment

Here's just a link to reiterate the comment of Kev: stackoverflow.com/questions/1154008/… (yes, I was about to flag you; with 6 flags you would've been kicked out).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.