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;
}
}
|
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.Select the equals() and hashCode() option:
Select the default options until you are asked to choose the fields you want
equals
to consider. Let’s assume that twoCourse
objects will be equal if they have the sametitle
andinstructor
values.Repeat the selections in the next two prompts for the
hashCode
andnull
fields.Click Finish. IntelliJ generates the
equals
andhashCode
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:
Line 17 performs the reference check on the object
o
.Line 18 performs the
null
check and class check ono
.Line 19 casts
o
as aCourse
object.Line 20 compares the
title
andinstructor
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!!!!!