Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if(listStr.size == 0){ versus if(listStr.isEmpty()){

Tags:

java

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?

like image 402
blue-sky Avatar asked Feb 18 '12 13:02

blue-sky


People also ask

Is isEmpty the same as size != 0?

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).

What is difference between isEmpty and size in Java?

size() can be O(1) or O(N), depending on the data structure ; . isEmpty() is never O(N).

Does isEmpty check for NULL list?

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.

What is the size of empty list in Java?

The size of an empty ArrayList is zero. ArrayList.


2 Answers

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.

like image 59
enzom83 Avatar answered Sep 21 '22 10:09

enzom83


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.

like image 36
JB Nizet Avatar answered Sep 21 '22 10:09

JB Nizet