猿问

检查 List 对象是否为空或未

我有一个域类,其中域类变量为空,返回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");

    }

}


慕哥6287543
浏览 197回答 2
2回答

qq_笑_17

null与空不同。列表的大小为 1,这意味着有 1 个对象(即使它的所有属性都为 null)。如果要检查其所有属性是否为空,则可以获取每个属性并检查它是否为空。您可以使用其他方法来确定属性是否为 not 的 null,然后只调用它。例如:public class DomainClass1 {&nbsp; &nbsp;String str1, str2;&nbsp; &nbsp;public boolean isEmpty() {&nbsp; &nbsp; &nbsp; if (this.str1 != null && this.str2 != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return false;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return true;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}现在调用它,如下所示:for (int i = 0; i < domain.size(); i++) {&nbsp; &nbsp;if (domain.get(i).isEmpty()) {&nbsp; &nbsp; &nbsp; // all fields null&nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; // not all are null&nbsp; &nbsp;}}

慕尼黑的夜晚无繁华

domain.isEmpty()&nbsp;它只是验证列表是空的,它不验证d的字段是空的,你可以在DomainClass1类中添加一个方法,就像这样public class DomainClass1 {&nbsp; &nbsp; private String test1;&nbsp; &nbsp; private String test2;&nbsp; &nbsp; private String test3;&nbsp; &nbsp; private String test4;&nbsp; &nbsp; ...&nbsp; &nbsp; public boolean isEmpty() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(test1 != null || test2 != null || test3 != null || test4 != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return true;&nbsp; &nbsp; }}那么你可以使用 d.isEmpty() 来替换 domain.isEmpty()
随时随地看视频慕课网APP

相关分类

Java
我要回答