0

I've a List of domain class where the domain class variables are null and the List returns 1 object. Can anyone help me validate the List for null. isEmpty dosn't seem to work.

Code

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");
    }
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Sam
  • 513
  • 1
  • 11
  • 27

2 Answers2

2

null is not the same as empty. Your list has the size of 1, meaning that there is 1 object (even if all properties of it are null). If you want to check if all its properties are not null then you can fetch each one and check if it is null or not.

You can have an additional method to determine whether the properties are null of not and then just invoke it. For eg:

public class DomainClass1 {
   String str1, str2;

   public boolean isEmpty() {
      if (this.str1 != null && this.str2 != null) {
         return false;
      } else {
         return true;
      }
   }
}

Now invoke it like :

for (int i = 0; i < domain.size(); i++) {
   if (domain.get(i).isEmpty()) {
      // all fields null
   } else {
      // not all are null
   }
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
2
domain.isEmpty() 

it just verify list isEmpty, it do not verify the d's fields isEmpty, you can add a method in DomainClass1 class just like this

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;
    }
}

then you can use d.isEmpty() to replace domain.isEmpty()

王星宇
  • 33
  • 6