是否有不允许空值的基本 Java Set 实现? [英] Is there a basic Java Set implementation that does not permit nulls?

查看:38
本文介绍了是否有不允许空值的基本 Java Set 实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java API Set界面状态:

The API for the Java Set interface states:

例如,有些实现禁止 null 元素,有些实现对其元素的类型有限制

For example, some implementations prohibit null elements and some have restrictions on the types of their elements

我正在寻找一个不需要排序的基本 Set 实现(如 ArrayList 提供 List 接口),并且不允许 null.TreeSet, HashSetLinkedHashSet 都允许空元素.此外,TreeSet 要求元素实现 Comparable.

I am looking for a basic Set implementation that does not require ordering (as ArrayList provides for the List interface) and that does not permit null. TreeSet, HashSet, and LinkedHashSet all allow null elements. Additionally, TreeSet has the requirement that elements implement Comparable.

目前似乎不存在这样的基本Set.有谁知道为什么?或者,如果确实存在我可以找到的地方?

It seems that no such basic Set exists currently. Does anyone know why? Or if one does exist where I can find it?

[Edit]:我不想允许 null ,因为在代码的后面,我的类将遍历集合中的所有元素并调用特定的方法.(我实际上在使用 HashSet>).我宁愿快速失败也不愿稍后失败,或者由于 null 在集合中而意外导致一些奇怪的行为.

: I do not want to allow nulls, because later in the code my class will iterate over all elements in the collection and call a specific method. (I'm actually using HashSet<MyRandomObject>). I would rather fail fast than fail later or accidentally incur some bizarre behavior due to a null being in the set.

推荐答案

与扩展特定实现相比,您可以轻松编写检查 nullSet 代理实现> s.这类似于 Collections.checkedSet.除了适用于任何实现之外,您还可以确保您已经覆盖了所有适用的方法.通过扩展具体集合发现了许多缺陷,然后在以后的版本中添加了额外的方法.

Better than extending a particular implementation, you can easily write a proxy implementation of Set that checks for nulls. This analogous to Collections.checkedSet. Other than being applicable to any implementation, you can also be sure that you have overridden all applicable methods. Many flaws have been found by extending concrete collections which then have additional methods added in later versions.

这篇关于是否有不允许空值的基本 Java Set 实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆