eyalgo
11/28/2011 - 4:17 AM

Example of Guava-based equals, hashCode, toString implementations

Example of Guava-based equals, hashCode, toString implementations

import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;

public class Address {

    ...

    @Override
    public boolean equals(Object obj) {

        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        final Address other = (Address) obj;
        return Objects.equal(this.houseNumber, other.houseNumber)
            && Objects.equal(this.street, other.street)
            && Objects.equal(this.city, other.city)
            && Objects.equal(this.stateOrProvince, other.stateOrProvince)
            && Objects.equal(this.country, other.country);

    }

    @Override
    public int hashCode() {

        return Objects.hashCode(
            this.houseNumber, this.street, this.city, this.stateOrProvince, this.country);

    }

    @Override
    public String toString() {

        return MoreObjects.toStringHelper(this)
            .add("houseNumber", houseNumber)
            .add("street", street)
            .toString();

    }

}