Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between isEmpty() and size() for hashmap if used under if condition?

Tags:

java

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?

like image 264
Radhicka Pardessi Avatar asked Nov 21 '25 14:11

Radhicka Pardessi


1 Answers

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.

like image 108
Tim Biegeleisen Avatar answered Nov 24 '25 05:11

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!