简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM