tags:

views:

3758

answers:

3

Let's say I have a method m() that takes an array of Strings as an argument. Is there a way I can just declare this array in-line when I make the call? i.e. Instead of:

String[] strs = {"blah", "hey", "yo"};
m(strs);

Can I just replace this with one line, and avoid declaring a named variable that I'm never going to use?

Thanks!

+26  A: 
m(new String[]{"blah", "hey", "yo"});
Draemon
That works! The syntax is not what I would expect, I tried a few things at random, but not this! Thanks :)
ZenBlender
No, it's pretty weird. Can't blame you for not guessing this one :)
Draemon
Just for future reference, this type of array is known as an anonymous array (as it has no name). searching "Anonymous array java" would've produced some results.
Falaina
@Falaina: Don't you just love those things you can only search for effectively once you've found them :P
Draemon
Trust me, I did search around a bit before posting, but couldn't find it, exactly the funny problem you're referring to. Stack Overflow saves the day once again! :)
ZenBlender
+7  A: 

Draemon is right. However, it would be easier for you if you declared m as taking varargs:

void m(String... strs) {
    // strs is seen as a normal String[] inside the method
}

m("blah", "hey", "yo"); // no [] or {} needed; each string is a separate arg here
Michael Myers
Thanks. I have used varargs in some situations and they are useful! Appreciated... :)
ZenBlender
+1  A: 

I'd like to add that the array initialization syntax is very succinct and flexible. I use it a LOT to extract data from my code and place it somewhere more usable.

As an example, I've often created menus like this:

Menu menu=initMenus(menuHandler, new String[]{"File", "+Save", "+Load", "Edit", "+Copy", ...});

This would allow me to write come code to set up a menu system. The "+" is enough to tell it to place that item under the previous item.

I could bind it to the menuHandler class either by a method naming convention by naming my methods something like "menuFile, menuFileSave, menuFileLoad, ..." and binding them reflectively (there are other alternatives).

This syntax allows AMAZINGLY brief menu definition and an extremely reusable "initMenus" method. (Yet I don't bother reusing it because it's always fun to write and only takes a few minutes+a few lines of code).

any time you see a pattern in your code, see if you can replace it with something like this, and always remember how succinct the array initialization syntax is!.

Bill K