Reputation: 552
I'm reviewing java and stumbled upon something like the following block of code
public Foo example()
Foo bar = new Foo(...);
...
return new Foo[]{bar};
what does Foo[]{bar} mean in this context? Is it returning an array of Foo objects populated by bar? Seems to be something really trivial but I'm not sure what how to search for it.
Upvotes: 0
Views: 160
Reputation: 2637
Upvotes: 1
Reputation: 49187
The equivalent code would be
Foo[] foos = new Foo[1];
foos[0] = bar;
return foos;
Upvotes: 1
Reputation: 8642
Yes, that's right. This constructs a single-element array of Foo
that consists only of the element bar
.
Upvotes: 1
Reputation: 1499860
Yes, it's creating an array with a single element, initially set to the value of bar
. You can use this syntax for more elements though, e.g.
new int[] { 1, 2, 3 }
This is an ArrayCreationExpression, as specified in section 15.10 of the Java Language Specification, using an ArrayInitializer as specified in section 10.6.
Upvotes: 4