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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:06:43  来源:igfitidea点击:

Removing null references from a HashSet

javanullsethashset

提问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 Setcan not contain the same value twice (including null, if it is supported by the specific Setimplementation), 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 nullbefore, because remove(null)will simply do nothing if the Setdoesn't contain null.

请注意,您甚至不需要检查nullbefore的存在,因为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).