+ 1

In the below code

@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } I dont understand why prime = 31. And why would happen if i keep another number. And why is result= 1.

24th Nov 2018, 4:49 PM
stephen haokip
stephen haokip - avatar
1 Odpowiedź
0
A very good article for the reson why prime is 31, is the following : https://www.javamex.com/tutorials/collections/hash_function_technical_2.shtml ---- -------- By multiplying, bits are shifted to the left. This uses more of the available space of hash codes, reducing collisions. By not using a power of two, the lower-order, rightmost bits are populated as well, to be mixed with the next piece of data going into the hash. The expression n * 31 is equivalent to (n << 5) - n.
26th Nov 2018, 7:05 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar