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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Course {

   private String title;
   private int credits;
   private String instructor;

   public Course (String title, int credits, String instructor) {
      this.title = title;
      this.credits = credits;
      this.instructor = instructor;
   }
}
  1. In the IntelliJ editor, right-click in the editor (or on the Course class name to be really deliberate), then select Generate from the menu.

  2. 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.

menu for shortcuts
  1. 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 Course objects will be equal if they have the same title and instructor values. Select Next.
menu selecting fields
  1. 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 Course class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Course {
    private String title;
    private int credits;
    private String instructor;

    public Course (String title, int credits, String instructor) {
        this.title = title;
        this.credits = credits;
        this.instructor = instructor;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Course course = (Course) o;
        return Objects.equals(title, course.title) && Objects.equals(instructor, course.instructor);
    }

    @Override
    public int hashCode() {
        return Objects.hash(title, instructor);
    }
}

Looking at the new equals method shows that it includes all of the best-practice components:

  1. Line 19 performs the reference check on the object o.
  2. Line 20 performs the null check and class check on o.
  3. Line 21 casts o as a Course object.
  4. Line 22 compares the title and instructor fields of the two objects.

Try it!

You can use the Generate option to add getters, setters, and toSting methods to the Course class.