Understanding HashMap <K, V>
Ok, here is a bit that I do not understand.
If you try to restore an object using the get() method and null is returned, it is still possible that null can be saved as the object associated with the key that you provided to the get() method. You can determine if this is the case by passing your object key to the containsKey() method for the map. This returns true if the key is saved on the map.
So, how containsKey() have to tell me if the value associated with the provided key is null ?
This is the link if you want to check. Page 553
Consider this simple piece of code:
Map<String, String> m = new HashMap<String, String>(); m.put("key1", "value1"); m.put("key2", null); System.out.println("m.get(\"key1\")=" + m.get("key1")); System.out.println("m.containsKey(\"key1\")=" + m.containsKey("key1")); System.out.println("m.get(\"key2\")=" + m.get("key2")); System.out.println("m.containsKey(\"key2\")=" + m.containsKey("key2")); System.out.println("m.get(\"key3\")=" + m.get("key3")); System.out.println("m.containsKey(\"key3\")=" + m.containsKey("key3")); As you can see, I entered two values ββinto the map, one of which is null. Thene, I asked for a map for three values: two of them are present (one is zero) and the other is not. Look at the result:
m.get("key1")=value1 m.containsKey("key1")=true m.get("key2")=null m.containsKey("key2")=true m.get("key3")=null m.containsKey("key3")=false The second and third are the hard part. key2 present with a null value, therefore, using get() , you cannot distinguish whether an element is in the map or is on the map with a null value. But using containsKey() , you can, since it returns boolean .
Map<String, Object> map = new HashMap<String, Object>(); map.put("Foo", null); System.out.println(map.containsKey("Foo")); System.out.println(map.containsKey("Boo")); OUTPUT:
true false get() returns null in two cases:
- The key does not exist on the map.
- A key exists, but the associated value is
null.
You cannot tell from get() , which is true. However, containsKey() will tell you if the key was present on the map, regardless of whether its associated value was null .