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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With