Aar*_*n K 27 java api null set
Java Set接口的API 指出:
例如,某些实现禁止
null元素,而某些实现对其元素的类型有限制
我正在寻找一个基本的Set实现,它不需要排序(如ArrayList为List接口提供)并且不允许null.TreeSet,HashSet和LinkedHashSet都允许null元素.另外,TreeSet要求元素实现Comparable.
目前似乎没有这样的基本Set存在.有谁知道为什么?或者,如果确实存在,我可以找到它?
[编辑]:我不想允许nulls,因为稍后在代码中我的类将迭代集合中的所有元素并调用特定方法.(我实际上正在使用HashSet<MyRandomObject>).我宁愿快速失败而不是失败,或者由于null在集合中而意外地产生一些奇怪的行为.
Tom*_*ine 27
比扩展特定实现更好,您可以轻松编写s Set检查的代理实现null.这类似于Collections.checkedSet.除了适用于任何实现之外,您还可以确保已覆盖所有适用的方法.通过扩展具体集合找到了许多缺陷,然后在以后的版本中添加了其他方法.
cdm*_*kay 22
我会说使用组合而不是继承...它可能更多的工作,但面对Sun可能对集合框架所做的任何更改,它会更稳定.
public class NoNullSet<E> implements Set<E>
{
/** The set that is wrapped. */
final private Set<E> wrappedSet = new HashSet<E>();
public boolean add(E e)
{
if (e == null)
throw new IllegalArgumentException("You cannot add null to a NoNullSet");
return wrappedSet.add(e);
}
public boolean addAll(Collection<? extends E> c)
{
for (E e : c) add(e);
}
public void clear()
{ wrappedSet.clear(); }
public boolean contains(Object o)
{ return wrappedSet.contains(o); }
... wrap the rest of them ...
}
Run Code Online (Sandbox Code Playgroud)
请注意,此实现不依赖于addAll调用add(这是一个实现细节,不应使用,因为无法保证在所有Java版本中都保持为true).
没有基本的专有Set实现忽略或约束null!有EnumSet,但是那个是用于包含枚举类型的裁缝.
但是,如果您使用Guava或Commons Collections,则可以避免创建自己的实现:
1.番石榴溶液:
Set noNulls = Constraints.constrainedSet(new HashSet(), Constraints.notNull());
Run Code Online (Sandbox Code Playgroud)
2. Commons Collections:
Set noNulls = new HashSet();
CollectionUtils.addIgnoreNull(noNulls, object);
Run Code Online (Sandbox Code Playgroud)