简体   繁体   English

为什么在HashSet中添加null不会引发异常,而在TreeSet中添加null会引发异常

[英]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. 为什么在HashSet中添加null不会引发Exception ,而是在TreeSet添加null引发Exception。

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

throws NullPointerException 抛出NullPointerException

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

Allow Null value to be added. 允许添加Null值。

Because the underlying data structure of a TreeSet is a Red-Black tree , which is a binary search tree and thus is sorted. 因为TreeSet的基础数据结构是Red-Black tree ,所以它是二进制搜索树,因此被排序。 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. 默认的Comparator不是null安全的,但是,如果您编写自己的支持null的Comparator,那么将null用作键将没有问题。

Simply put, that is how it has been implemented. 简而言之,这就是它的实现方式。 According to the Java specification for HashSet , 根据HashSet的Java规范,

This class permits the null element 此类允许使用null元素

And according to the javadoc for TreeSet in the add method it throws: 而根据的Javadoc TreeSet中添加它抛出方法:

NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements NullPointerException-如果指定元素为null且此集合使用自然顺序,或其比较器不允许使用null元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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