Skip to content
Advertisement

Map.ofEntries gives Null Pointer Exception on checking NULL key using containsKey()

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, and Map.copyOf static 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 UnsupportedOperationException to 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 null keys and values. Attempts to create them with null keys or values result in NullPointerException.

In contrast, the javadoc of HashMap says:

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, 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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement