Java: 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?

20
задан Svish 14 April 2011 в 10:35
поделиться