Helpful Eclipse template to implement equals/hashCode in Java

Goal

To make it easier to implement/override the methods equals and hashCode in Java

Description

This recipe provides you with an Eclipse IDE template to help on the implementation of the methods equals and hashCode in Java.

The implementation of these two methods are not as easy as it may seem at first (I would recommend reading the book Effective Java: Second edition, particularly on the detailed explanation of the things we need to take into account for the implementation of those two methods).

Notice, however, that this recipe does not intend to explain how those methods should be implemented but only to help on that implementation!

How to

Next, there’s the steps you should take in order to create the Eclipse IDE template that will help you implementing the equals/hashCode methods in all your future Java projects šŸ™‚

  1. Open your Eclipe IDE and click on the top level option Window > Preferences
  2. On the left side panel, go to Java > Editor > Templates
  3. Click on the button “New…” on the right side of that panel
  4. Set “equalsTo” in the popup window’s Name field
  5. Select “Java” in the Context field
  6. Make sure the flag “Automatically insert” is checked
  7. Add a description such as “Template to help on the implementation of a equals and hashCode methods.”
  8. And finally, insert the following in the Pattern field:
    @Override
    public boolean equals(final Object other) {
      if (this == other) {
        return true;
      }
      if (!(other instanceof ${type})) {
        return false;
      }
      return equalsTo((${type})other);
    }
    
    @Override
    public int hashCode() {
      int result = 13;
      result = 29 * result + (${propGetter} != null ? ${propGetter}.hashCode() : 0);
      // TODO: Add as many lines as necessary
      return result;
    }
    
    private boolean equalsTo(final ${type} other) {
      // TODO: Add as many lines as necessary
      return java.util.Objects.equals(${propGetter}, other.${propGetter})${cursor};
    }
    
  9. Click “Ok” and your template should be ready to be used

To test your new template, create a new Java class and write something like “equa” and click CTRL+SPACE to force the autocomplete from Eclipse to run. Select your new template named equalsTo and when the code gets inserted, simply replace the variables type with the name of your class and the propGetter variable with the field or getter method name that should be taken into account for the implementation of equality for your class (add as many lines as necessary, one per field/property to be verified).

Notice also that, as very well pointed out by my friend Nuno Oliveira, in Eclipse, there already is an alternative and useful feature to help on the implementation of the equals and hashCode methods (use which one you prefer and best suits your needs). Simply right click on your class’s source code and go to Source > Generate hashCode and equals (select the class fields that you want to use for the implementation and you are ready to go).

Explanations

This simple template does not solve the difficulties on the implementation of the equals and hashCode methods in Java but it helps you to:

  1. Not forget to respect the contract of the Object class in what concerns the relation (read the documentation on the Java class for both methods) between the equals and the hashCode methods
  2. Guarantee that, if two different instances point to the same reference, they are for sure equal (the first if statement on the template)
  3. Guarantee that two different object references may only be equal if they are both instances of the same class (the if statement with the instanceof clause)
  4. Remember the developer that the implementation should take into account the fields or getter methods of that class and deal with checks for null references. That is taken care of by the equals methods on the Java 7 Objects class (you may use your own implementation if you are using a version lower than Java 7 or use the Objects class from google. Whichever version you use, the equals methods on the Objects class is implemented as the following):
    public static boolean equals(Object a, Object b) {
      return (a == b) || (a != null && a.equals(b));
    }
    

Leave a comment