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?
Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.
The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.
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.
In the Eclipse preferences go to Java > Editor > Templates.
In there you can create a new template. The pattern could look like:
@Override public int hashCode() { return Objects.hash(one, two, three, four/*, ...*/); }
I'm not sure if there's a variable that will properly enumerate your fields however.
You might want to look at some further explanations on these templates
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With