List<String> listStr = new ArrayList<String>(); if(listStr.size == 0){ }
versus
if(listStr.isEmpty()){ }
In my view one of the benefits of using listStr.isEmpty()
is that it doesn't check the size of the list and then compares it to zero, it just checks if the list is empty. Are there any other advantages as I often see if(listStr.size == 0)
instead of if(listStr.isEmpty())
in codebases? Is there is a reason it's checked this way that I am not aware of?
Basically, in implementations of some lists the method isEmpty() checks if the size is zero (and therefore from the point of view of performance they are practically equivalent).
size() can be O(1) or O(N), depending on the data structure ; . isEmpty() is never O(N).
isEmpty() doesn't check if a list is null . If you are using the Spring framework you can use the CollectionUtils class to check if a list is empty or not.
The size of an empty ArrayList is zero. ArrayList.
The answers to this question could give you the answer. Basically, in implementations of some lists the method isEmpty()
checks if the size is zero (and therefore from the point of view of performance they are practically equivalent). In other types of lists (for example the linked lists), however, counting items require more time than to check if it is empty or not.
For this reason it is always convenient to use the method isEmpty()
to check if a list is empty. The reasons for which such a method is provided in all types of lists are also related to the interface, since ArrayList
, Vector
and LinkedList
implement the same List
interface: this interface has the isEmpty()
method; then, each specific type of list provides its implementation of isEmpty()
method.
No, there's no reason. isEmpty()
expresses the intent more clearly, and should be preferred. PMD even has a rule for that. It doesn't matter much, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With