IntelliJ IDEA shortcuts for equals() and hashCode()


In IntelliJ IDEA, you can use the Alt + Insert (Windows/Linux) or ⌘Cmd + N (macOS) shortcut keys to generate the hashCode() and equals() methods.

You may like : Contract between hashCode() and equals() methods.

Step 1: Go to the class where you want to generate the equals() and hashCode() method. Press the Alt + Insert (Windows/Linux) or ⌘Cmd + N (macOS) keys together from the keyboard and click on the equals() and hashCode() from the pop-up.

IntelliJ IDEA shortcuts for equals() and hashCode()

Step 2: Choose the template from the dropdown and click on the Next. I will keep the IntelliJ IDEA template.

IntelliJ IDEA template for equals() and hashCode()

Step 3: Select the fields to include in the equals() method and click on the Next.

IntelliJ IDEA- choose the fields for equals() method

Step 4: Again, select the fields to include in the hashCode() method and click on the Next.

IntelliJ IDEA- choose the fields for hashCode() method

Step 5: Leave non-null fields as blank and click on the Finish.

IntelliJ IDEA- leave it as blank

The equals() and hashCode() method will be generated in the class and final result will look like as follow:

Department.java
package org.websparrow;

public class Department {

    private long id;
    private String name;
    private String desc;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Department that = (Department) o;

        if (id != that.id) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        return desc != null ? desc.equals(that.desc) : that.desc == null;
    }

    @Override
    public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (desc != null ? desc.hashCode() : 0);
        return result;
    }
}

References

  1. IntelliJ IDEA- Generate Getter & Setter Shortcut Key
  2. IntelliJ IDEA- Import/Open multiple project in single Window
  3. IntelliJ IDEA – public static void main shortcut

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.