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 signature

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.

The body

Study the equals method above. You should always include the following steps:

  1. Check for self comparison.

  2. Use instanceof to make sure that the parameter is the right type.

  3. If the parameter is the right type, cast the Object to the correct class.

  4. Compare the chosen fields and return a true or false, depending on if the Objects are equal.

  5. 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 the hashcode method.

  • the hashCode method should always generate equal values for equal objects.

  • If possible, equals and hashCode should use unmodifiable fields. If this isn’t possible and the Object will mutate over time, the Object should not be used as a key in a hashed collection.