Skip to content

Instantly share code, notes, and snippets.

@rocketraman
Last active April 27, 2023 04:53
  • Star 15 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rocketraman/1399080 to your computer and use it in GitHub Desktop.
Example of Guava-based equals, hashCode, toString implementations
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.equals(this.houseNumber, other.houseNumber)
&& Objects.equals(this.street, other.street)
&& Objects.equals(this.city, other.city)
&& Objects.equals(this.stateOrProvince, other.stateOrProvince)
&& Objects.equals(this.country, other.country);
}
@Override
public int hashCode() {
return Objects.hash(
this.houseNumber, this.street, this.city, this.stateOrProvince, this.country);
}
}
@facundofarias
Copy link

Guava has now migrated Objects to MoreObjects.

@rocketraman
Copy link
Author

@facundofarias Thanks, I updated the Gist to use MoreObjects instead of the deprecated Objects.toStringHelper. The "equal" and "hashCode" methods are still present in Objects because their naming does not conflict with the JDK Objects method.

@rocketraman
Copy link
Author

Created a new Gist for JDK7+ / Guava 18+ users here: https://gist.github.com/rocketraman/653af25ee3bf72ca497f.

@SupaHam
Copy link

SupaHam commented Apr 5, 2017

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