Java – why does NetBeans generate hashcode () in its way?
I've been using NetBeans for java development. There are some things I just rely on working without asking how These include the automatically generated hashcode () and equals () methods
The equals method is simple, but I find the hashcode method a little mysterious I don't understand why I choose a multiplier and apply what it does
import java.util.Arrays; import java.util.Objects; public class Foo { int id; String bar; byte[] things; @Override public int hashCode() { int hash = 7; hash = 89 * hash + this.id; hash = 89 * hash + Objects.hashCode(this.bar); hash = 89 * hash + Arrays.hashCode(this.things); return hash; } }
Searching for documents, this website has nothing to do with Google's "NetBeans generate hash code" Who is familiar with this generation strategy here? Why does NetBeans use it?
Editor: Thank you for your answer! Especially because of this answer on the linked so question, I understand the logic of using prime numbers in a hashcode method more comprehensively However, another aspect of the problem that no one has really solved so far is how NetBeans choose the prime number it makes for the generated method Hash fields and other multipliers (89 in my example) seem to vary depending on various factors of the class
For example, if I add a second string to the class, hashcode () becomes
public int hashCode() { int hash = 7; hash = 13 * hash + this.id; hash = 13 * hash + Objects.hashCode(this.bar); hash = 13 * hash + Objects.hashCode(this.baz); hash = 13 * hash + Arrays.hashCode(this.things); return hash; }
So why do NetBeans choose these specific primes over others?
Solution
This is an optimization designed to better allocate hash values Eclipse does the same Why use a prime number in hashcode? And why does Java's hashcode() in string use 31 as a multiplier
This is unnecessary Even return 0; To meet the equals / hashcode contract The only reason is that hash based data structures perform better under good distributed hash values
Some would call it premature optimization I think it's ok because it's a) free (generated) and b) widely recognized (almost every ide does this)