Overriding Object.equals()


When overriding the Object.equals() method, there are a number of conditions that must be met. Some of these conditions can be enforced programmatically, such as:

  1. The parameter must be of type Object. Using a specific type will result in unintuitive behaviour at least, because two .equals() methods will exist, and it might not be clear in all cases which method will be called
  2. If Object.equals() is overridden, Object.hashCode() should be overridden too. This follows from the requirement that equal objects must have equal hash codes. If no suitable hashCode() can be constructed, the method should throw an UnsupportedOperationException

Since 0.6


Bad code:

Good code:

public boolean equals(MyClass s) {
    return this.name.equals(s.name);
public boolean equals(Object o) {
    if (!(o instanceof MyClass)) {
        return false;
    else {
        return this.name.equals(((MyClass)o).name);
public int hashCode() {
    return this.name.hashCode();

Available quick fixes

The quick fix for this code check adds a hashCode() method if it does not yet exist.