繁体   English   中英

CollectionUtils.isNotEmpty()比null检查更好吗?

[英]Is CollectionUtils.isNotEmpty() better than a null check?

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

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

代替

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

是否有任何理由/优势使用CollectionUtils.isNotEmpty(coll)而不是其他? 谢谢。

这里没有真正的优势。 即使有,也会非常小。 它只是阻止了Iterator的创建和执行分支指令,这就是它的全部内容。

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

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

相当于:

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

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

反编译显示

public static boolean isEmpty(Collection coll) {
    return coll == null || coll.isEmpty();
}

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

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

假设你的例子

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。

如果我们使用null表达式,如果coll不为null但是为空,则结果将不同

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为true,但是在循环for甚至没有一次传递。

当然, if表达式coll != null && coll.isNotEmpty()执行与CollectionUtils.isNotEmpty(coll)相同的工作。

因此,在集合coll != null情况下,不建议使用对null的测试编程方式。 这是处理不当的极端条件的情况,这可能是不希望的结果的来源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM