java 从 HashSet 中删除空引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7468493/
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
Removing null references from a HashSet
提问by Mouna Cheikhna
Is there a simple way of removing null references from a HashSet like
the way we can delete them from a List using list.removeAll(Collections.singletonList(null))
?
有没有一种简单的方法可以从 HashSet 中删除空引用,就像我们可以使用从 List 中删除它们的方式一样list.removeAll(Collections.singletonList(null))
?
回答by Joachim Sauer
Since a Set
can not contain the same value twice (including null
, if it is supported by the specific Set
implementation), simply doing set.remove(null)
would be sufficient.
由于 aSet
不能包含两次相同的值(包括null
,如果特定Set
实现支持),只需执行即可set.remove(null)
。
Note that you don't even need to check for the existence of null
before, because remove(null)
will simply do nothing if the Set
doesn't contain null
.
请注意,您甚至不需要检查null
before的存在,因为remove(null)
如果Set
不包含null
.
回答by Tikhon Jelvis
A HashSet
, being a set, only contains one "copy" of any object, which also means that it can only contain one instance of null
. Thus, you can just use HashSet.remove(null)
.
AHashSet
作为一个集合,只包含任何对象的一个“副本”,这也意味着它只能包含 的一个实例null
。因此,您可以只使用HashSet.remove(null)
.