V.S
V.S

Reputation: 165

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.

Upvotes: 6

Views: 19666

Answers (2)

Daan van der Kallen
Daan van der Kallen

Reputation: 533

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.

Upvotes: 14

DanielBarbarian
DanielBarbarian

Reputation: 5333

Simply put, that is how it has been implemented. According to the Java specification for HashSet,

This class permits the null element

And according to the javadoc for TreeSet in the add method it throws:

NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

Upvotes: 1

Related Questions