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?
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, sinceArrayList,VectorandLinkedListimplement the sameListinterface: this interface has theisEmpty()method; then, each specific type of list provides its implementation ofisEmpty()method.