为了账号安全,请及时绑定邮箱和手机立即绑定

检查 List 对象是否为空或未

检查 List 对象是否为空或未

慕哥6287543 2022-08-03 16:43:37
我有一个域类,其中域类变量为空,返回1个对象。任何人都可以帮我验证 . 似乎不起作用。ListListListnullisEmpty法典public static void main(String[] args) {    DomainClass1 d = new DomainClass1();    List<DomainClass1> domain = new ArrayList<>();    d.setTest1(null);    d.setTest2(null);    d.setTest3(null);    d.setTest4(null);    domain.add(d);    System.out.println(domain);    if (domain.isEmpty()) {        System.out.println("is empty");    }}
查看完整描述

2 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

null与空不同。列表的大小为 1,这意味着有 1 个对象(即使它的所有属性都为 null)。如果要检查其所有属性是否为空,则可以获取每个属性并检查它是否为空。


您可以使用其他方法来确定属性是否为 not 的 null,然后只调用它。例如:


public class DomainClass1 {

   String str1, str2;


   public boolean isEmpty() {

      if (this.str1 != null && this.str2 != null) {

         return false;

      } else {

         return true;

      }

   }

}

现在调用它,如下所示:


for (int i = 0; i < domain.size(); i++) {

   if (domain.get(i).isEmpty()) {

      // all fields null

   } else {

      // not all are null

   }

}


查看完整回答
反对 回复 2022-08-03
?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

domain.isEmpty() 

它只是验证列表是空的,它不验证d的字段是空的,你可以在DomainClass1类中添加一个方法,就像这样


public class DomainClass1 {

    private String test1;

    private String test2;

    private String test3;

    private String test4;

    ...

    public boolean isEmpty() {

         if(test1 != null || test2 != null || test3 != null || test4 != null) {

             return false;

         }

         return true;

    }

}

那么你可以使用 d.isEmpty() 来替换 domain.isEmpty()


查看完整回答
反对 回复 2022-08-03
  • 2 回答
  • 0 关注
  • 195 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号