我有一个List
域类变量为 null 且 List
返回 1 个对象。谁能帮我验证List
对于 null
。 isEmpty
似乎不起作用。
代码
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");
}
}
最佳答案
null
与空不同。您的列表的大小为 1,这意味着有 1 个对象(即使它的所有属性均为 null)。如果你想检查它的所有属性是否都不为空,那么你可以获取每个属性并检查它是否为空。
您可以使用一个附加方法来确定属性是否为 null 或 not,然后调用它。例如:
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
}
}
关于java - 检查List对象是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55102394/