5

What is the difference between both of result.

  1. When I've null value with key

  2. When key itself is not exist

In above both condition result is null. So how can i identify 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
Houssam Badri
  • 2,441
  • 3
  • 29
  • 60
  • 1
    possible duplicate of [Key existence check in HashMap](http://stackoverflow.com/questions/3626752/key-existence-check-in-hashmap) – Joe Dec 10 '14 at 11:09

3 Answers3

9

While get returns the same result for null value and non-existing key, containsKey doesn't:

map.containsKey(1) would return true.

map.containsKey(2) would return false.

In addition, if you iterate over the keys of the Map (using keySet()), 1 will be there and 2 won't.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Hashmap returns null if no Value is mapped to the key. So this can be solved by your code also:

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

Reference Here

Riad
  • 3,822
  • 5
  • 28
  • 39
0

Make a check for if the value is null to avoid the null prints.

pseudo code:

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