Search code examples
javaobjectis-empty

isEmpty issue while comparing java object


Currenty I have this NULL object for Employee Details to pass if employee details object created is empty

public static final EmployeeDetails NULL = new EmployeeDetails();

But I want to remove this now and use my regular EmployeeDetails object.

I was checking EmployeeDetails obj is empty or not by doing this if(!EmployeeDetails.NULL.equals(empDetails))

but now I dont have that object so I won't be able to do that way. I tried this way but got error saying isEmpty is not defined.

if(!empDetails.isEmpty())

Can someone tell me what I am suppose to do with this.

Thanks


Solution

  • isEmpty() is not defined because you did not define it. This funciton is not included in the handful of methods you get directly from Object and, in any case, an empty condition for your own objects should be defined by you since only you know the internal structure.

    Of course, it all depends on what do you need because one person can take an isEmpty() method as valid by doing a simple null check while other person can make a field-by-field check.

    In your case, just define an isEmpty method in your class. For example:

    public boolean isEmpty() {
        //your condition here, for example, I take an EmployeeDetails object
        //as empty if it has no employee associated (assuming you can associate
        //an employee to it).
        return employee == null;
    }
    

    Remember to define WHEN do you consider this object to be empty and code the method with that in mind.