Last active
April 27, 2023 04:53
-
-
Save rocketraman/1399080 to your computer and use it in GitHub Desktop.
Example of Guava-based equals, hashCode, toString implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
I would like to point out that checking exact equality of classes in equals
should be used carefully. If the class is final, then there is no problem. However, if sub classes may be considered equal with others, then the equals
will always fail.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Created a new Gist for JDK7+ / Guava 18+ users here: https://gist.github.com/rocketraman/653af25ee3bf72ca497f.