1

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

7
  • 5
    How about IntStream.empty().toArray()? Commented Feb 6, 2018 at 23:13
  • What do you mean by "pass", show some code, that is not working please. Commented Feb 6, 2018 at 23:15
  • IntStream.empty().toArray() - this is what looking for. Commented Feb 6, 2018 at 23:16
  • 1
    int[] is an own type in the JVM. When you say Collections.emptyList().toArray(), you get an Object[](which would contain Integer,i. e. boxed values, if you had values in the list) Commented Feb 6, 2018 at 23:20
  • 3
    It's not clear what you have against new int[] {} or new int[0]. Commented Feb 6, 2018 at 23:30

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"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." here it is worth adding rule saying we should "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
3

try this one

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.