java 为什么HashSet加null不抛出异常,而TreeSet加null会抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36785418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why adding null in HashSet does not throw Exception,but adding null in TreeSet throw Exception
提问by V.S
Why adding null
in HashSet
does not throw Exception
,but adding null
in TreeSet
throw Exception.
为什么加null
在HashSet
没有抛出Exception
,但添加null
在TreeSet
抛出异常。
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
增值。
回答by Daan van der Kallen
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.
因为 TreeSet 的底层数据结构是一棵红黑树,它是一棵二叉搜索树,因此是经过排序的。要对其进行排序,必须有一个 Comparator 来确定一个值是否等于、小于或大于另一个值。默认的 Comparator 不是空安全的,但是如果您编写自己的 Comparator 支持空值,则使用空值作为键没有问题。
回答by DanielBarbarian
Simply put, that is how it has been implemented. According to the Java specification for HashSet,
简而言之,这就是它的实施方式。根据HashSet的 Java 规范,
This class permits the null element
此类允许空元素
And according to the javadoc for TreeSetin the addmethod it throws:
根据它抛出的add方法中TreeSet的 javadoc :
NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
NullPointerException - 如果指定的元素为 null 并且此集合使用自然排序,或者其比较器不允许 null 元素