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
instanceof
to make sure that the parameter is the right type. -
If the parameter is the right type, cast the
Object
to the correct class. -
Compare the chosen fields and return a true or false, depending on if the
Objects
are equal. -
Override the
hashCode
method 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 thehashcode
method. -
the
hashCode
method should always generate equal values for equal objects. -
If possible,
equals
andhashCode
should use unmodifiable fields. If this isn’t possible and theObject
will mutate over time, theObject
should not be used as a key in a hashed collection.