714

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?

Ben
  • 54,723
  • 49
  • 178
  • 224
DivideByHero
  • 19,715
  • 24
  • 57
  • 64

8 Answers8

1087
m(new String[]{"blah", "hey", "yo"});
Draemon
  • 33,955
  • 16
  • 77
  • 104
  • 106
    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 Jul 20 '09 at 14:55
  • 3
    It resembles casting. I think that's how I'll think of it so I don't have to google it the once in a bluemoon I need to do this. – ArtOfWarfare Aug 21 '12 at 16:10
  • 4
    This is the rare instance where a code-only answer is totally acceptable, and in fact, maybe even preferable. – Max von Hippel Mar 08 '20 at 23:25
  • 1
    @Falaina The array doesn't have a different type (anonymous) just because the reference isn't stored in a variable of the immediate scope. The array still has Object identity, its reference passed and bound to method param. Never heard of referring to Objects as anonymous. I see no comparison with anonymous classes, where there is a new class definition with no name. Sorry for old post reply, looking for info about potential inline arrays regards to post Valhalla – bourne2program Jul 18 '20 at 22:26
131

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
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
35

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()
...
Community
  • 1
  • 1
Gibolt
  • 42,564
  • 15
  • 187
  • 127
30

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" });
Antonio Carlos
  • 770
  • 9
  • 19
  • 48
    you actually don't need to create an array, you can do simply: `Arrays.asList("string1", "string2", ...)` – Elias Dorneles Jan 08 '13 at 17:59
  • 2
    Possibly useful point: You can't do this with primitives. You'll end up with a single-element `List` of `type[]` where `type` is that primitive. e.g. `Arrays.asList([some ints])` results in a `List`. – Salem Jan 19 '17 at 20:29
  • @Antonio Carlos: no, it is not. You can call `set` on the returned `List` and it will modify the array. – Holger Oct 09 '17 at 15:35
  • In that case you should use `List.of(1, 2, 3)`. – Jelle Blaauw Jan 14 '22 at 10:55
12

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.

Mahpooya
  • 529
  • 1
  • 6
  • 18
7

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

ArrayUtils.toArray("elem1","elem2")
Shravan Ramamurthy
  • 3,896
  • 5
  • 30
  • 44
  • It is an alternative, however it has additional functional calls adding to the stack which are unnecessary. – CybeX Aug 13 '18 at 14:41
3

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
  • 62,186
  • 18
  • 105
  • 157
  • 5
    This would also be preferable to do as varargs. Also, anyone who likes typing code out for "fun" deserves a downvote! Coding is about solving new problems, not typing. Oh wait, this is Java ;-) – mjaggard Dec 13 '12 at 09:51
  • 1
    You are right, when I wrote this I hadn't used varargs much--and I used array initialization quite a bit before varargs existed in java. The one part I'd still prefer arrays for is that if you define it as an aray you can make it a constant at the top of the file instead of inline data, and you can also extract it to a config file – Bill K Dec 13 '12 at 17:14
  • By the way, 8 years later I'd have to say I now find myself using annotations to do nearly all the things that I used to use initialized string arrays for. – Bill K Feb 27 '17 at 22:37
0

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

Vokail
  • 630
  • 8
  • 27
  • 10
    Just a couple of issues here: 1. Please ensure that in your posts and profile you make it abundantly clear that you are affiliated with Espresso4J (please see our [FAQ#promotion]) 2. Please be careful posting links to your own website on fairly old posts (especially boilerplate answers like this one and [this one](http://stackoverflow.com/questions/1473868/why-cant-i-create-a-new-java-array-inline/7300580#7300580)) - it comes off as very spammy and raises flags which will dent your rep. – Kev Sep 04 '11 at 21:49
  • @Kev ah sorry. I've clarified that I'm the developer of the fine Espresso4J project now:) – Jonathan Weatherhead Sep 05 '11 at 01:51