簡體   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