Search code examples
javanullpointerexceptionequalscoding-style

Clean way of avoiding NullPointerException in equals checks


I have an address object that I want to create an equals method for. I could have made this quite simple by doing something like the following (shortened a bit):

public boolean equals(Object obj) 
{
    if (this == obj)
        return true;

    if (obj == null)
        return false;

    if (getClass() != obj.getClass())
        return false;

    Address other = (Address) obj;

    return this.getStreet().equals(other.getStreet())
        && this.getStreetNumber().equals(other.getStreetNumber())
        && this.getStreetLetter().equals(other.getStreetLetter())
        && this.getTown().equals(other.getTown());
}

Problem is, some of these might be null. I will in other words get a NullPointerException if there is no street letter in this address.

How can I write this in a clean way while taking null values into account?


Solution

  • You can use a helper method like

    public static boolean isEqual(Object o1, Object o2) {
        return o1 == o2 || (o1 != null && o1.equals(o2));
    }