user1578872
user1578872

Reputation: 9028

Java - Empty int array

I need to pass an empty int array.

new int[]{} -> this works.

But, is there anyway with the below approach?

Collections.emptyList().toArray() -> I am unable to cast this to int[] array.

The method signature,

public void checkVersions(final int[] versions)

This is the method to be called. There are case where i need to pass some empty int[].

Thanks

Upvotes: 1

Views: 305

Answers (2)

TheTechGuy
TheTechGuy

Reputation: 1608

try this one

int[] array = IntStream.empty().toArray();

Upvotes: 3

Ray
Ray

Reputation: 686

This might be considered off-topic to the question, but I still want to provide you with the following thougts:

When you write code, you should write it in a way that makes it as simple as possible to read later on by somebody who has no clue what the code is supposed to do.

Therefore, "new int[0]" or "new int[]{}" are much better than "IntStream.empty().toArray()". Why? Because the first two make it clear that you are constructing an int[] and that it is empty. The later solution with the IntStream requires more thought (thus has higher cognitive load) as you first see the IntStream, of which and empty stream is created. This empty stream of integers is then converted to an array. So you don't see the data type that is being created and you have an extra step (the conversion).

I would rate (personal thought!) other solutions than "new int[0]" or "new int[]{}" to be tricky code. Don't try to be fancy with a plain "empty integer array" creation, it will just cause pain to anybody who reads the code.

Now, I don't want to talk bad about you interest in alternatives, I only want to avoid that you put such code into production. I hope this message came along.

Upvotes: 4

Related Questions