java - Good hashCode() Implementation -
the accepted answer in best implementation hashcode method gives seemingly method finding hash codes. i'm new hash codes, don't quite know do.
for 1), matter nonzero value choose? 1
other numbers such prime 31
?
for 2), add each value c? if have 2 fields both long
, int
, double
, etc?
did interpret right in class:
public myclass{ long a, b, c; // these fields //some code , methods public int hashcode(){ return 37 * (37 * ((int) (a ^ (a >>> 32))) + (int) (b ^ (b >>> 32))) + (int) (c ^ (c >>> 32)); } }
- the value not important, can whatever want. prime numbers result in better distribution of
hashcode
values therefore preferred. - you not necessary have add them, free implement whatever algorithm want, long fulfills
hashcode
contract:
- whenever invoked on same object more once during execution of java application,
hashcode
method must consistently return same integer, provided no information used in equals comparisons on object modified. integer need not remain consistent 1 execution of application execution of same application.- if 2 objects equal according
equals(object)
method, callinghashcode
method on each of 2 objects must produce same integer result.- it not required if 2 objects unequal according
equals(java.lang.object)
method, calling hashcode method on each of 2 objects must produce distinct integer results. however, programmer should aware producing distinct integer results unequal objects may improve performance of hash tables.
there algorithms can considered not hashcode
implementations, simple adding of attributes values being 1 of them. reason is, if have class has 2 fields, integer
a, integer
b , hashcode()
sums these values distribution of hashcode
values highly depended on values instances store. example, if of values of a between 0-10 , b between 0-10 hashcode
values between 0-20. implies if store instance of class in e.g. hashmap
numerous instances stored in same bucket (because numerous instances different a , b values same sum put inside same bucket). have bad impact on performance of operations on map, because when doing lookup elements bucket compared using equals()
.
regarding algorithm, looks fine, similar 1 eclipse generates, using different prime number, 31 not 37:
@override public int hashcode() { final int prime = 31; int result = 1; result = prime * result + (int) (a ^ (a >>> 32)); result = prime * result + (int) (b ^ (b >>> 32)); result = prime * result + (int) (c ^ (c >>> 32)); return result; }
Comments
Post a Comment