HashMap null issue

What is the difference between the result.

  • When I have a null value with a key

  • When the key itself does not exist

In the above example, both conditions result are zero. So how can I determine my key value

Map map = new HashMap();
map.put(1,null);
System.out.println(map.get(1));
System.out.println(map.get(2));

Answer:

null

null
+4
source share
3 answers

While it getreturns the same result for a value nulland a nonexistent key, it containsKeydoes not:

map.containsKey(1)will return true.

map.containsKey(2)will return false.

Also, if you iterate over the keys Map(using keySet()), it 1will be there, 2not it will be.

+8
source

Hashmap null, Value. , :

if( map.get(1) != null ){
     //
}

+1

Check if the value is null to avoid zero fingerprints.

pseudo code:

//For inputting
if(object != null){
   map.put(1, object);
}
//For getting the value
if(value != null){
     map.get(value)
  }
0
source

All Articles