Writing an Equals method
For this example, let’s create a Car class:
public class Car{
private final String model;
private final int numDoors;
private double gasMilage;
private String color;
public Car(String model, int numDoors, double gasMilage, String color){
this.model = model;
this.numDoors = numDoors;
this.gasMilage = gasMilage;
this.color = color;
}
@Override
public boolean equals(Object o){
if(o == this) return true;
if (!(o instanceof Car)) return false;
Car other = (Car) o;
// Using model and numDoors because these are final variables.
return other.getModel().equals(getModel()) &&
other.getNumDoors() == getNumDoors();
}
@Override
public int hashCode(){
// using the same fields as used in the equals method
return getModel().hashCode() + getNumDoors();
}
public String getModel(){
return model;
}
public in getNumDoors(){
return numDoors;
}
}
The method signature of the equals method is ALWAYS:
@Override public boolean equals(Object o);
The @Override annotation is not necessary, but is recommended. This ensures that you have the correct method signature.
You will learn why this is important next week when you go over inheritance.
Study the equals method above. You should always include the following steps:
-
Check for self comparison.
-
Use
instanceofto make sure that the parameter is the right type. -
If the parameter is the right type, cast the
Objectto the correct class. -
Compare the chosen fields and return a true or false, depending on if the
Objectsare equal. -
Override the
hashCodemethod using the same fields.
The hashCode method ensures that your class will work correctly with more advanced data structures.
Additional Guidelines
-
If you override the
equals, you must override thehashcodemethod. -
the
hashCodemethod should always generate equal values for equal objects. -
If possible,
equalsandhashCodeshould use unmodifiable fields. If this isn’t possible and theObjectwill mutate over time, theObjectshould not be used as a key in a hashed collection.