ChatGPT解决这个技术问题 Extra ChatGPT

Any way to declare an array in-line?

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?

An IDE that supports re-factoring would allow you to in-line strs automatically.

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

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.
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.
This is the rare instance where a code-only answer is totally acceptable, and in fact, maybe even preferable.
@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
D
Dave Jarvis

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

pretty nice syntax, but with this method you can have only one array parameter, and it must be the last one. So, you can't do: void m(String... strs, Integer... intgrs) for example.
blefoot is right. But you can do void m(Integer i, Double d, String... str)
@MichaelMyers What is the meaning of (String ... strs)
@KasunSiyambalapitiya: Click the link in my answer.
C
Community

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

But you can't do doSomething({"blah", "hey", "yo"}), which is what the original question was asking about.
A
Antonio Carlos

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

you actually don't need to create an array, you can do simply: Arrays.asList("string1", "string2", ...)
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<int[]>.
@Antonio Carlos: no, it is not. You can call set on the returned List and it will modify the array.
In that case you should use List.of(1, 2, 3).
M
Mahpooya

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.


S
Shravan Ramamurthy

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

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

It is an alternative, however it has additional functional calls adding to the stack which are unnecessary.
B
Bill K

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


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 ;-)
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
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.
V
Vokail

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


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) 2. Please be careful posting links to your own website on fairly old posts (especially boilerplate answers like this one and this one) - it comes off as very spammy and raises flags which will dent your rep.
@Kev ah sorry. I've clarified that I'm the developer of the fine Espresso4J project now:)