The method "equals" (and "hashCode") will go into many of our "proper objects" (classes). The reason is that Java's default implementation for "equals" is to use "==" (identity). Not typically what we want.
So if we have two separate tuples (different objects/variables) say:
Comparing objects is a fundamental operation, especially when testing. We'd like to be able to do this:
boolean okay = object1.equals(equals2);
The default "equals" (inherited from Object) is usually not sufficient because it only returns true if the two objects have the same object identity (i.e. they are the exact same object).
Therefore, we need to override (implement) "equals" and "hashCode" on our model classes.
An example is below. Note that we have added a method "safeEquals". That is just a general helper method that takes care of cases where either/both objects being compared are null.
When we add these three methods to a new class we can just copy the code below and tweak it to fit our new class.
public int hashCode() {
int hashCode = 7;
hashCode = 31 * hashCode + (getName()==null ? 0 : getName().hashCode());
hashCode = 31 * hashCode + (getStateAbbrev()==null ? 0 : getStateAbbrev().hashCode());
hashCode = 31 * hashCode + (getZip()==null ? 0 : getZip().hashCode());
return hashCode;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof City))
return false;
City other = (City)o;
return
safeEquals(this.getName(), other.getName())
&& safeEquals(this.getStateAbbrev(), other.getStateAbbrev())
&& safeEquals(this.getZip(), other.getZip());
}
private boolean safeEquals(Object a, Object b) {
//If only one is nil, then false, use XOR*/
if (a==null ^ b==null)
return false;
//We now know both are null, or not null, check for condition #1 first*///If either is null, they both are
if (a==null)
return true;
//Finally a safe equals
return a.equals(b);
}
public String getName() {
return this.name;
}
public String getStateAbbrev() {
return this.stateAbbrev;
}
public String getZip() {
return this.zip;
}