Coding in the small with Google Collections: Objects.equal and hashCode
Part 4 in a Series.Objects.equal(Object,Object) and Objects.hashCode(Object...) provide built-in null-handling, which makes implementing your own
equals()
and hashCode()
methods easy.Before:
public boolean equals(Object o) {
if (o instanceof Order) {
Order that = (Order)o;
return (address != null
? address.equals(that.address)
: that.address == null)
&& (targetArrivalDate != null
? targetArrivalDate.equals(that.targetArrivalDate)
: that.targetArrivalDate == null)
&& lineItems.equals(that.lineItems);
} else {
return false;
}
}
public int hashCode() {
int result = 0;
result = 31 * result + (address != null ? address.hashCode() : 0);
result = 31 * result + (targetArrivalDate != null ? targetArrivalDate.hashCode() : 0);
result = 31 * result + lineItems.hashCode();
return result;
}
After:
public boolean equals(Object o) {
if (o instanceof Order) {
Order that = (Order)o;
return Objects.equal(address, that.address)
&& Objects.equal(targetArrivalDate, that.targetArrivalDate)
&& Objects.equal(lineItems, that.lineItems);
} else {
return false;
}
}
public int hashCode() {
return Objects.hashCode(address, targetArrivalDate, lineItems);
}
This is much more concise than handwritten or IDE-generated code. As a special treat, there's deepEquals and deepHashcode methods that 'do the right thing' for arrays and nested arrays, that otherwise use identity for
equals
and hashCode
.Part 5