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.
CodePudding user response:
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.
CodePudding user response:
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
.
CodePudding user response:
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.