2

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?

Gayan Mettananda
  • 1,498
  • 14
  • 21
  • 4
    They're the same (well, actually, they're opposites of each other). But probably neither will prevent your null pointer exception. – Dawood ibn Kareem Mar 12 '19 at 04:44
  • How can I nullify Null pointer exception incase such case? – Radhicka Pardessi Mar 12 '19 at 04:50
  • 1
    Well, _assuming_ your null pointer exception is happening because your `Map` is null, you should check whether your `Map` is null. But maybe the exception is happening for some other reason - it's impossible to tell without seeing your code. – Dawood ibn Kareem Mar 12 '19 at 04:51

4 Answers4

6

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 2
    +1, but `isEmpty()` isn't necessarily *just* a convenience method: it's specified by `java.util.Map`, and in at least one implementation of that interface (namely [`java.util.concurrent.ConcurrentSkipListMap`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListMap.html)) it's significantly faster than `size()`. – ruakh Mar 12 '19 at 05:03
  • @ruakh Good stuff, I did not know this. – Tim Biegeleisen Mar 12 '19 at 05:05
  • If there is no key-value pair in hashmap ,is there any case/chance that size() would return non zero value? – Radhicka Pardessi Mar 12 '19 at 05:08
  • @RadhickaPardessi The size should never go negative AFAIK. – Tim Biegeleisen Mar 12 '19 at 05:12
  • @ruakh I expected this to be the case for `LinkedList`, but surprisingly, it's not. It just inherits the [`AbstractCollection` implementation](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/AbstractCollection.java). – jpmc26 Mar 12 '19 at 16:14
  • @jpmc26: Yeah, `java.util.LinkedList` keeps its size in a field for that purpose. I think the only JDK collections that compute their size dynamically are those optimized for concurrency, such as `ConcurrentLinkedQueue`. Most of these define `isEmpty()` in a more-optimal way than `size()`; the only exception I see offhand is `ConcurrentHashMap`, which *could* exit early but *doesn't*. (I haven't looked exhaustively though the JDK, though, and I haven't even glanced at non-JDK collections such as those provided by Guava.) – ruakh Mar 12 '19 at 20:25
5

First do the null check on Map object and then Empty check to avoid NullPointerException

if(map != null && !map.isEmpty())
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
1

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:

  1. it is more expressive (the code is easier to read and to maintain)

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

Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
0

map.size() == 0 is equal to map.isEmpty(). E.g. IntelliJ IDEA has inspection to always use isEmpty() instead of size() == 0.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35