IntelliJ IDEA 2016.2 Help

Generating equals() and hashCode()

On this page:

Basics

public boolean equals(Object obj)

This method returns true, if an object passed to it as an argument is equal to the object on which this method is invoked.

public int hashCode()

This method returns the integer hash code value for the object on which this method is invoked.

Generating equals() and hashCode() methods

To generate equals() and hashCode() methods, follow these steps:

  1. Do one of the following:
    • On the main menu, choose Code | Generate.
    • Right-click the editor and choose Generate on the context menu.
    • Press Alt+Insert.
  2. From the pop-up list that opens in the editor, select equals() and hashCode() option to open the Generate equals() and hashCode() wizard.
  3. Follow the steps of the wizard:
    • On the first page of the wizard, select or clear the check boxes to accept subclasses, and use getters during code generation. You can also select a velocity template from the Template drop-down list to generate the code or create a custom template.
    • On the second page of the wizard, select the fields that should be used to determine equality, and click Next.
    • On the third page, select the fields to generate hash code.

      Note that only the fields that were included in the equals() method, can participate in creating hash code. All these fields are selected by default, but you can unselect them, if necessary.

      Click Next.

    • On the fourth page of the wizard, select the fields that contain non-null values. This optional li help the generated code avoid check for null and thus improves performance. Click Finish.

Example

public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FixedRateCurrencyExchangeService that = (FixedRateCurrencyExchangeService) o; if (Double.compare(that.rate, rate) != 0) return false; return true; } public int hashCode() { long temp = rate != +0.0d ? Double.doubleToLongBits(rate) : 0L; return int (temp ^ (temp >>> 32)); }

See Also

Last modified: 5 September 2016