Any way to declare an array in-line?

JavaArrays

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Update: Kotlin Answer

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()
...

Solution 5 - Java

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.

Solution 6 - Java

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!.

Solution 7 - Java

Other option is to use ArrayUtils.toArray in org.apache.commons.lang3

ArrayUtils.toArray("elem1","elem2")

Solution 8 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDivideByHeroView Question on Stackoverflow
Solution 1 - JavaDraemonView Answer on Stackoverflow
Solution 2 - JavaMichael MyersView Answer on Stackoverflow
Solution 3 - JavaAntonio CarlosView Answer on Stackoverflow
Solution 4 - JavaGiboltView Answer on Stackoverflow
Solution 5 - JavaMahpooyaView Answer on Stackoverflow
Solution 6 - JavaBill KView Answer on Stackoverflow
Solution 7 - JavaShravan RamamurthyView Answer on Stackoverflow
Solution 8 - JavaJonathan WeatherheadView Answer on Stackoverflow