How to teach eclipse to generate compact equals() and hashCode() from the jdk 7 Objects class?

eclipse, equals, hashcode, java

Solution

`hashCode` and `equals` generation using the Java 7 `Objects` class has now been implemented in Eclipse. I was working on the feature request 424214 back in August 2018 and my contributions were merged in the JDT UI codebase shortly afterwards (see commit f543cd6).

Here's an overview of the new option in the Source > Generate hashCode() and equals... tool:

This has been officially released in Eclipse 4.9 in September 2018. Simply download the latest version of Eclipse (downloads can be found here), or install the latest available software with the following update site: http://download.eclipse.org/releases/latest

In addition to this new feature, arrays are now handled more cleverly. The generation will use the `Arrays.deepHashCode` and `Arrays.deepEquals` methods in a number of cases where it would previously incorrectly prefer the standard `Arrays.hashCode` and `Arrays.equals` alternatives.

Problem

Some days ago we switched to Java 7 within my Company - finally! Jay \o/ So I found out about the `Objects` class and was astonished how short the methods `hashCode()` and `equals()` were realized, reducing a lot of boylerplate code compared to the ones generated by eclipse per default (ALT+SHIFT+S --> H). I was wondering if I could change the default behaviour of the eclipse generated `hashCode()` and `equals()`? I'd love to see this: ``` @Override public int hashCode() { return Objects.hash(one, two, three, four/*, ...*/); } ``` instead of this: ``` @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((one == null) ? 0 : one.hashCode()); result = prime * result + ((two == null) ? 0 : two.hashCode()); result = prime * result + ((three == null) ? 0 : three.hashCode()); result = prime * result + ((four== null) ? 0 : four.hashCode()); // ... return result; } ``` The same goes for `equals()`. This is the article I got this from. Any ideas how to realize this best?

Original source

Related problems