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.
Step 2: Choose the template from the dropdown and click on the Next. I will keep the IntelliJ IDEA template.
Step 3: Select the fields to include in the equals() method and click on the Next.
Step 4: Again, select the fields to include in the hashCode() method and click on the Next.
Step 5: Leave non-null fields as blank and click on the Finish.
The equals() and hashCode() method will be generated in the class and final result will look like as follow:
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
- IntelliJ IDEA- Generate Getter & Setter Shortcut Key
- IntelliJ IDEA- Import/Open multiple project in single Window
- IntelliJ IDEA – public static void main shortcut