Implementing Good hashCode function in java? -
i know days inbuilt utilities available hashcodebuilder apache commons lang trying understand how implement myself , came across example of hascode function employee class @ http://en.wikipedia.org/wiki/java_hashcode()
everywhere on google, same kind of technique suggested multiplying non 0 value odd prime number , summing instance variable(do instance variable).
questions:-
1)why can't return employeeid hascode becoz aways unique. simple , serves hascode purpose. agreed if not unique need kind of technique. right?
2)even if employee id not unique, why suggested multiply odd prime number? why taking damn integer not considered good?
update:-
peter ran example mentioned printed
[0, 32, 64, 96, 128, 160, 192, 224, 288, 256, 352, 320, 384]
[0, 32, 64, 96, 128, 160, 192, 224, 288, 256, 352, 320, 384]
i assume output yoy expected understand concept mentioned in answer
[373, 343, 305, 275, 239, 205, 171, 137, 102, 68, 34, 0]
[0, 34, 68, 102, 137, 171, 205, 239, 275, 305, 343, 373]
as suggested in comment example demonstrated unique hashcode can end in same bucket. how example demonstrated behaviour? mean 373 integers , 0 integers2 end in same bucket ?
how prime number helping in example , how 34 not have helped?
why can't return employeeid hascode becoz aways unique. simple , serves hascode purpose. agreed if not unique need kind of technique. right?
it's uniqueness not important. multiplying prime way of merging multiple fields 1 hashcode, sounds have one, wont make difference.
even if employee id not unique, why suggested multiply odd prime number? why taking damn integer not considered good?
if multiply number lowest bit of hashcode be? how random/useful it?
note: every hashcode() integer unique, right combination of integer values , when reduced capacity of hashmap, map same bucket. in example, entries appear in reverse order added because every entry mapped same bucket.
hashset<integer> integers = new hashset<>(); (int = 0; <= 400; i++) if ((hash(i) & 0x1f) == 0) integers.add(i); hashset<integer> integers2 = new hashset<>(); (int = 400; >= 0; i--) if ((hash(i) & 0x1f) == 0) integers2.add(i); system.out.println(integers); system.out.println(integers2); static int hash(int h) { // function ensures hashcodes differ // constant multiples @ each bit position have bounded // number of collisions (approximately 8 @ default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); }
prints
[373, 343, 305, 275, 239, 205, 171, 137, 102, 68, 34, 0] [0, 34, 68, 102, 137, 171, 205, 239, 275, 305, 343, 373]
Comments
Post a Comment