如上所述,这取决于您要测试的内容以及您的逻辑是如何构建的。
假设你的例子
if (CollectionUtils.isNotEmpty(coll)) {
for (String str : coll) {
System.out.println("Branch 1. Collection is not empty.");
}
}
else {
System.out.println("Branch 2. Collection is empty.");
}
在这个例子中,我们可以看到,总是执行 Branch1 或 Branch2。
coll
如果我们使用空表达式,如果不为空但为空,结果会有所不同
if (coll != null) {
for (String str : coll) {
System.out.println("Branch1. Collection is not empty.");
}
}
else {
System.out.println("Branch2. Collection is empty.");
}
如果集合coll
不为 null 但为空,则 Branch1 或 Branch2 都不会执行,因为条件coll != null
为真,但在循环for
中甚至没有一次通过。
当然,if
表达式coll != null && coll.isNotEmpty()
做同样的工作CollectionUtils.isNotEmpty(coll)
。
因此,仅在集合的情况下使用 null 测试是不可取的编程方式coll != null
。这是一个处理不当的极端条件的情况,这可能是不良结果的根源。