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

    Pop up menu for IntelliJ's generate option.
  2. Select the equals() and hashCode() option:

    Select ``equals`` option.
  3. Select the default options until you are asked to 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 fields to compare.
  4. Repeat the selections in the next two prompts for the hashCode and null fields.

  5. Click Finish. IntelliJ generates the equals and hashCode methods:

     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
    26
    27
    28
    import java.util.Objects;
    
    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 instanceof Course)) return false;
          Course course = (Course) o;
          return title.equals(course.title) &&
                   instructor.equals(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 17 performs the reference check on the object o.

  2. Line 18 performs the null check and class check on o.

  3. Line 19 casts o as a Course object.

  4. Line 20 compares the title and instructor fields of the two objects.

5.4.1. Try It!

Use the Generate option to add getters, setters, and a toString method to the Course class.

COOL!!!!!