Reputation: 20355
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?
Upvotes: 735
Views: 473758
Reputation: 47287
You can directly write the array in modern Java, without an initializer. Your example is now valid. It is generally best to name the parameter anyway.
String[] array = {"blah", "hey", "yo"};
or
int[] array = {1, 2, 3};
If you have to inline, you'll need to declare the type:
functionCall(new String[]{"blah", "hey", "yo"});
or use varargs (variable arguments)
void functionCall(String...stringArray) {
// Becomes a String[] containing any number of items or empty
}
functionCall("blah", "hey", "yo");
Hopefully Java's developers will allow implicit initialization in the future
Kotlin has made working with arrays so much easier! For most types, just use arrayOf
and it will implicitly determine type. Pass nothing to leave them empty.
arrayOf("1", "2", "3") // String
arrayOf(1, 2, 3) // Int
arrayOf(1, 2, "foo") // Any
arrayOf<Int>(1, 2, 3) // Set explict type
arrayOf<String>() // Empty String array
Primitives have utility functions. Pass nothing to leave them empty.
intArrayOf(1, 2, 3)
charArrayOf()
booleanArrayOf()
longArrayOf()
shortArrayOf()
byteArrayOf()
If you already have a Collection
and wish to convert it to an array inline, simply use:
collection.toTypedArray()
If you need to coerce an array type, use:
array.toIntArray()
array.toLongArray()
array.toCharArray()
...
Upvotes: 38
Reputation: 4096
Other option is to use ArrayUtils.toArray in org.apache.commons.lang3
ArrayUtils.toArray("elem1","elem2")
Upvotes: 8
Reputation: 559
You can create a method somewhere
public static <T> T[] toArray(T... ts) {
return ts;
}
then use it
m(toArray("blah", "hey", "yo"));
for better look.
Upvotes: 13
Reputation: 1580
As Draemon says, the closest that Java comes to inline arrays is new String[]{"blah", "hey", "yo"}
however there is a neat trick that allows you to do something like
array("blah", "hey", "yo")
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
Upvotes: 0
Reputation: 192025
Draemon is correct. You can also declare 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
Upvotes: 132
Reputation: 780
Another way to do that, if you want the result as a List inline, you can do it like this:
Arrays.asList(new String[] { "String1", "string2" });
Upvotes: 31
Reputation: 62789
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!.
Upvotes: 4