alex28
alex28

Reputation: 552

What does the following java statement mean

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

Answers (6)

r0ast3d
r0ast3d

Reputation: 2637

  • Create an instance of the class Foo on line 2 when you say new Foo(...)
  • In the next line you are returning an array.
  • The "type" of the array is "Foo"
  • A member in the array that you are returning is "bar"

Upvotes: 1

Johan Sjöberg
Johan Sjöberg

Reputation: 49187

The equivalent code would be

Foo[] foos = new Foo[1];
foos[0] = bar;
return foos;

Upvotes: 1

Mike Daniels
Mike Daniels

Reputation: 8642

Yes, that's right. This constructs a single-element array of Foo that consists only of the element bar.

Upvotes: 1

Jon Skeet
Jon Skeet

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

CamelSlack
CamelSlack

Reputation: 573

It is returning an array with the contents being bar.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272227

Yes. It's an array of one element. That element being bar.

Upvotes: 3

Related Questions