Why adding null in HashSet does not throw Exception,but adding null in TreeSet throw Exception

V.S picture V.S · Apr 22, 2016 · Viewed 12.3k times · Source

Why adding null in HashSet does not throw Exception,but adding null in TreeSet throw Exception.

Set<String>  s = new TreeSet<String>();
        s.add(null);

throws NullPointerException

Set<String>  s = new HashSet<String>();

Allow Null value to be added.

Answer

Daan van der Kallen picture Daan van der Kallen · Apr 22, 2016

Because the underlying data structure of a TreeSet is a Red-Black tree, which is a binary search tree and thus is sorted. For it to be sorted there must be a Comparator that determines whether a value is equal, lower or greater than another value. The default Comparator is not null-safe, if you'd however write your own Comparator that has support for null it would be no problem to use null as a key.