Reputation: 1005
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.
Upvotes: 16
Views: 16393
Reputation: 1225
I was under the same impression that Treemap
does not allows any null key, but while using java 6
I found I am able to add first element with null
key in treemap, but with java 8
it is not the case.
Map<String, Date> productStartDatesBySourceProductID = new TreeMap<String, Date>();
Upvotes: 1
Reputation: 30019
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())
Upvotes: 38