-1

When checking for an empty array, array.length < 1 And array.length == 0 will get you the same result but which is preferred or does it matter at all? I can see the reason array.length == 0 is preferred is that the length of an array will never be less than 0 and it’s more precise to put it that way.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Fran
  • 98
  • 1
  • 12
  • _"which is preferred"_... and then you say _"I can see the reason array.length == 0 is preferred... it’s more precise to put it that way"_ :) I think you pretty much know the answer already. – M A Feb 23 '22 at 15:40
  • Also [this thread](https://stackoverflow.com/questions/2369967/how-can-i-check-whether-an-array-is-null-empty) might be relevant if you consider a `null` array to be "empty". – Nexevis Feb 23 '22 at 15:41

3 Answers3

2

They are identical from the JVM point of view.

From the programmer point of view is more readable array.length == 0.

Generally speaking, try to let your code readable, and only if you have any performance gap to solve try to investigate if it is possible to write the same code in a more efficient way also if it is less human-readable.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • 1
    Aside from the valid complaint about size of array (vs. e.g. size of ArrayList), I'd say they communicate different intents to code readers. One focuses on "is it empty?", the other on "is an element available?" The semantic difference is more obvious with larger numbers (e.g. "are two elements available") though also the alternative ("is size not 0 or 1?") would cost more instructions, so it's not a perfect parallel. But if you envision your "1 element required" might one day turn into "2 elements required", i'd prefer `< 1` over `== 0`. So... context. – Amadan Feb 23 '22 at 15:45
0

No, it does not matter at all. There will be same number of bytecode instructions for both i < 1 and i == 0.

However, if you're checking against empty array, from the readability perspective, it would be better to check i == 0.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
  • 2
    Not correct. Test against zero can be done with dedicated bytecode instructions, so `i == 0` has one instruction less than `i < 1`. Not that this one byte matters much… – Holger Mar 10 '22 at 17:59
0

The JLS definition of an empty array is:

The number of variables may be zero, in which case the array is said to be empty

So, the difference between the two in terms of this definition can be thought of as:

  • array.length == 0 - "the array is empty"
  • array.length < 1 - "the array is not not empty"

The one without the double negative is easier.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243