Java Reference
In-Depth Information
The generator also generates much safer and efficient versions of these methods
than most people have the patience to write, especially if you have many fields
to consider.
If these methods are already defined in the class, IDEA informs you with
the corresponding dialog.
NOTE
From the generator pop-up, select the option to create hashCode and equals
methods. Doing so launches a wizard with three steps (see figure 3.20).
In the first step, select the fields that should be used to determine equality.
Each of the selected field's values will be compared, and objects will be consid-
ered equal only if all the field values specified here are equivalent. Click Next
to continue.
In the second step, select the fields that should be used to generate the hash
code for the object. In keeping with the specification requirements, you can't
include fields in the hash code that aren't in the equals method, so the list con-
tains only the fields you selected previously. By default, they are all selected, but
you can disable some of them if necessary without violating the equality rule.
Click Next to continue.
In the third step, select the fields that you can guarantee contain non-null val-
ues. This step is optional, but if you know a value will never be null (for example,
a constant, or a value defined in the constructor), then the generated code will
skip the check for null for a small improvement in efficiency. Click Finish to com-
plete the wizard and generate your methods. The code generated by our example
can be seen in listing 3.1.
Figure 3.20
The code generator needs to know
which fields are used to determine
equality within the equals and
hashCode methods of the class.
Search WWH ::




Custom Search