Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why null key is not allowed in TreeMap?

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.

like image 438
Amol Patil Avatar asked Feb 08 '18 14:02

Amol Patil


People also ask

Why null insertion is not possible in TreeMap?

TreeSet adds elements to it according to their natural order. This internally compares the elements with each other using the compareTo (or compare) method. If you try to compare any object with a null value using one of these methods, a NullPointerException will be thrown.

Can TreeMap have null keys?

A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It contains only unique elements. It cannot have null key but can have multiple null values.

Why null key is not allowed in HashMap?

Now you must be wondering why HashTable doesn't allow null and HashMap do? The answer is simple. In order to successfully store and retrieve objects from a HashTable, the objects used as keys must implement the hashCode method and the equals method. Since null is not an object, it can't implement these methods.

Can we have null key in HashMap TreeMap?

HashMap allows storing at most one null key and many null values. However, TreeMap doesn't allow a null key but may contain many null values. If we're using a TreeMap with a user-defined Comparator, then it depends on the implementation of the compare() method how null values get handled.


1 Answers

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())

like image 72
kapex Avatar answered Sep 23 '22 16:09

kapex