Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 260
V.S Avatar asked Jul 16 '26 13:07

V.S


1 Answers

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.

like image 145
Daan van der Kallen Avatar answered Jul 20 '26 03:07

Daan van der Kallen