我有一个给定对象的Set
的方法。它委托给的方法要求Set
不包含任何null元素。我想check the precondition在委托之前的方法中,Set
早期不包含任何null元素。显而易见的代码是这样的:
public void scan(Set<PlugIn> plugIns) {
if (plugIns == null) {
throw new NullPointerException("plugIns");
} else if (plugIns.contains(null)) {
throw new NullPointerException("plugIns null element");
}
// Body
}
但这是不正确的,因为如果
Set.contains()
实现本身不允许使用null元素,则 NullPointerException
可能会抛出Set
。在这种情况下,捕获然后忽略NullPointerException
将可以工作but would be inelegant。是否有一种巧妙的方法来检查此前提条件?Set
接口是否存在设计缺陷?如果Set
实现可能永远不包含null,为什么不要求Set.contains(null)
始终返回false
呢?还是有一个isNullElementPermitted()
谓词? 最佳答案
最简单的方法是枚举Set并检查null。
public void scan(Set<PlugIn> plugIns) {
if (plugIns == null) throw new NullPointerException("plugIns");
for (PlugIn plugIn : plugIns) {
if (plugIn == null) throw new NullPointerException("plugIns null element");
}
}
关于java - 检查Set是否不包含null的简洁方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8787480/