这是针对“Is there a basic Java Set implementation that does not permit nulls?”的后续问题。 (感谢所有帮助答案的人)在添加到集合之前,检查集合为null的不同方法有什么优缺点?
看来,做这件事的方法,因为Sun没有提供像这样简单的东西,所以是使用包装器/代理。这似乎很直接。我想知道的是以下两种添加集合的方式有什么优点/缺点,还是有另一种更好的方法?
方法#1
public boolean addAll(Collection<? extends E> c) {
if (null == c) {
throw new NullPointerException("c cannot be null");
}
/*
* This seems like a terrible abuse of exceptions when
* all I want to do is check the set for a null.
*
* However, simply running through each element of the
* Collection may provide much worse performance for large
* collections. And according to the Collection API, the
* contains method may throw NullPointerExceptions if the
* collection implementation does not allow null elements.
*/
boolean collectionContainsNull = false;
try {
collectionContainsNull = c.contains(null);
} catch (NullPointerException safeToIgnore) {
/* Safe to ignore since we do not want nulls */
}
if (collectionContainsNull) {
throw new NullPointerException("c cannot contain null elements");
}
this.wrapperSet.addAll(c);
}
方法2
public boolean addAll(Collection<? extends E> c) {
if (null == c) {
throw new NullPointerException("c cannot be null");
}
E[] a = (E[])c.toArray();
/*
* We have to iterate through the entire collection to check for
* a null. This won't take advantage of any optimizations that
* c.contains may be using.
*
* We don't call add(e) here because if we hit a null midway through
* we would violate the condition that the set remains unchanged
* on error.
*/
for (E e : a) {
if (null == e) {
throw new NullPointerException("c cannot contain nulls");
}
}
this.wrapperSet.addAll(a);
}
提前感谢!
的指定者的预期好处是,一旦创建阵列的本地副本,如果原始集合要么支票或之后在通话过程修改addAll不会有问题。 – 2009-02-27 17:00:01