簡體   English   中英

Check is a Collection Object is Null in Java

[英]Check is a Collection Object is Null in Java

我有一個 Collection Object 結構如下:

[
  {
    "maBN": 8,
    "address": "American",
    "_type": "Person",
    "name": "Anna Johnson",
    "parent_of": [
      {
        "maBN": 10,
        "address": "American",
        "_type": "Person",
        "name": "Abraham Napoleon",
        "parent_of.type": "natural",
        "_id": 63
      },
      {
        "maBN": 11,
        "address": "American",
        "_type": "Person",
        "name": "William Napoleon",
        "parent_of.type": "natural",
        "_id": 64
      }
    ],
    "_id": 61
  }
]

我想檢查它是否 null 是這樣的:

[
  {}
]

這是我的 function 來檢查它:

public Collection<Object> getFamilyTree(@RequestParam Long id, @RequestParam String gender) {
        if (personService.getFamilyTree(id,gender).toArray().length!=0)
        {
            return personService.getFamilyTree(id, gender);
        }
        else{
            return personService.getFamilyTree2Gen(id,gender);
        }
    }

使用 personService.getFamilyTree 和 personService.getFamilyTree2Gen 返回一個集合

我應該怎么辦? 非常感謝,對不起我的英語不好!

使用下面的實用方法來了解集合 null 是空的還是空的。

public static <T> boolean isEmpty(Collection<T> c) {
   if (c == null) {
       return true;
   } else {
       return c.size() == 0;
   }
}

public static <T> boolean isNotEmpty(Collection<T> c) {
   return !isEmpty(c);
}

然后像這樣寫你的代碼

Collection<Object> familyTree = personService.getFamilyTree(id, gender);
if (isNotEmpty(familyTree)) {
    return familyTree;
} else {
    return personService.getFamilyTree2Gen(id,gender);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM