I have to deal with NullPointerException
which is occurring on Hashmap
. Shall I use map.isEmpty()
or (map.size() > 0
) inside if
condition?
Which one is better?
I have to deal with NullPointerException
which is occurring on Hashmap
. Shall I use map.isEmpty()
or (map.size() > 0
) inside if
condition?
Which one is better?
Here are the implementations for size()
and isEmpty()
in the HashMap
class:
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
So, HashMap#isEmpty()
just checks the same size
variable which size()
returns. It is mainly just a convenience method. One reason why you might want to use isEmpty()
over manually comparing the size is that the former makes it clearer what your code is actually checking.
First do the null check on Map
object and then Empty
check to avoid NullPointerException
if(map != null && !map.isEmpty())
map.size()
is O(1) , while complexity of map.isEmpty()
is also the same, so basically no difference between them from point of complexity and execution.
If you carefully look at
public boolean isEmpty() {
return size == 0;
}
It is doing nothing but returning size==0;
Other reasons to prefer .isEmpty()
over .size()
can be:
Just FYI, map.size()
has various advantages over map.isEmpty() when it comes to deal with collection, like you can do below operation just by map.size()
not by later.
String str = "abcd";
Map<Integer,String> map = new HashMap<>();
String[] strings = str.split("");
for(String s: strings) {
map.put(map.size(), s);
}
Reference: Converting string to Map<Integer,String> in java 8
map.size() == 0
is equal to map.isEmpty()
. E.g. IntelliJ IDEA has inspection to always use isEmpty()
instead of size() == 0
.