IntelliJ Generator Shortcut
Instead of cutting, pasting, and refactoring old code to ensure that you create a well-structured
hashCode() method whenever you define your own
equals() method, you can use IntelliJ’s code generation tool! Just right-click within your class file and select Generate > equals and hashCode and follow the prompts.
Let’s use a Course class to demonstrate:
In the IntelliJ editor, right-click in the editor (or on the
Courseclass name to be really deliberate), then select Generate from the menu.
Select equals() and hashCode(). You will be asked which template to use. Select java.util.Objects.equals() and hashCode() (java 7+). This is all we will select for now.
- When you are asked to Choose fields to be included in equals() choose the fields you want equals to consider. Let’s assume that two
Courseobjects will be equal if they have the same
instructorvalues. Select Next.
- The next menu will ask you to Choose the fields you want included in hashCode(). This should match the fields you selected when you were setting up the
equals()method. Select Create.
You should now see two new methods in the
Looking at the new
equals method shows that it includes all of the best-practice components:
- Line 19 performs the reference check on the object
- Line 20 performs the
nullcheck and class check on
- Line 21 casts
- Line 22 compares the
instructorfields of the two objects.
You can use the Generate option to add getters, setters, and
toSting methods to the