7

许多建议在下面的用例中使用CollectionUtils.isNotEmpty(coll)而不是。coll != null

if (CollectionUtils.isNotEmpty(coll)) {
    for (String str : coll) {
    }
}

代替

if (coll != null) {
    for (String str : coll) {
    }
}

这里有什么理由/优势可以CollectionUtils.isNotEmpty(coll)代替其他吗?谢谢。

4

4 回答 4

8

这里没有真正的优势。即使有,也将非常小。它只是防止创建Iterator和执行分支指令,仅此而已。

只有当集合为空时,才会出现这个小优势。以下循环:

for (String str : coll) {
   ...
}

相当于:

for (Iterator<String> iterator = col.iterator(); iterator.hasNext();) {
   String str = iterator.next();
   ...
}

当集合为空时,检查会CollectionUtils.isNotEmpty(coll)阻止循环执行。因此 noIterator在内存中创建并且没有调用hasNext()O(1)这是以调用为代价的coll.isEmpty()

于 2015-06-05T12:28:33.917 回答
5

反编译揭示

public static boolean isEmpty(Collection coll) {
    return coll == null || coll.isEmpty();
}
于 2015-06-05T12:31:23.583 回答
2

如上所述,这取决于您要测试的内容以及您的逻辑是如何构建的。

假设你的例子

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。这是一个处理不当的极端条件的情况,这可能是不良结果的根源。

于 2019-01-19T20:36:03.933 回答
1

问题是,当集合不为空时,集合仍然可以是空的。因此,在您的情况下,这取决于您选择的偏好。

于 2015-06-05T12:27:14.570 回答