Skip to content

Instantly share code, notes, and snippets.

@rocketraman
Last active April 27, 2023 04:53
Show Gist options
  • Save rocketraman/1399080 to your computer and use it in GitHub Desktop.
Save rocketraman/1399080 to your computer and use it in GitHub Desktop.
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();
}
}
@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