Why null key is not allowed in TreeMap?

Amol Patil picture Amol Patil · Feb 8, 2018 · Viewed 8.8k times · Source

I am trying to understand the concept behind Java Collection framework and came along to this question - Why null key is not allowed in TreeMap?

Its giving NullPointerException if we try to add null key in TreeMap.

Tried to google the Internal Working of TreeMap and found something like TreeMap uses RedBlack tree algorithm which is difficult to understand for me right now and I am working on it.

TreeMap is a Red-Black tree based NavigableMap implementation.In other words , it sorts the TreeMap object keys using Red-Black tree algorithm.

Please clear me, While other two implementation of the Map interface allows null as a key, then why TreeMap is not allowing to add null as a key?

I would like to thanks for explanation in advance.

Answer

kapex picture kapex · Feb 8, 2018

TreeMap does allow null keys. The default natural ordering comparator is the one that throws the exception.

From the documentation of TreeMap.put:

NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys

The easiest way to allow null values is to create the TreeMap with a comparator like Comparator.nullsFirst(Comparator.naturalOrder()) or Comparator.nullsLast(Comparator.naturalOrder())