I was fetching key from a constant map earlier using HashMap.
On passing a NULL key at containsKey(), I used to get FALSE.
To make the code look fancy, I tried java-8 over it. So, instead of HashMap, I started using Map.ofEntries to build my map
Surprisingly, I got Null Pointer Exception when a Null key was passed to containsKey() method
String str = null;
Map<String,String> hashMap = new HashMap<>();
hashMap.put("k1", "v1");
System.out.print(hashMap.containsKey(str)); // This gives false
Map<String,String> ofEntriesMap = Map.ofEntries( Map.entry("k1", "v1"));
System.out.print(ofEntriesMap.containsKey(str)); // Why this gives Null Pointer Exception ?
I am unable to figure out, why it is behaving differently at Map.ofEntries.
What is the best way to handle this situation ?
Advertisement
Answer
The javadoc of Map says:
Unmodifiable Maps
The
Map.of,Map.ofEntries, andMap.copyOfstatic factory methods provide a convenient way to create unmodifiable maps. The Map instances created by these methods have the following characteristics:
- They are unmodifiable. Keys and values cannot be added, removed, or updated. Calling any mutator method on the Map will always cause
UnsupportedOperationExceptionto be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.- They disallow
nullkeys and values. Attempts to create them withnullkeys or values result inNullPointerException.- …
In contrast, the javadoc of HashMap says:
Hash table based implementation of the
Mapinterface. This implementation provides all of the optional map operations, and permitsnullvalues and thenullkey. (TheHashMapclass is roughly equivalent toHashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.…