why we can't return employeeId as hascode becoz it will aways be unique. Its simple and serves the hascode purpose. Agreed if it is not unique probably we need that kind of technique. Is that right?
It's uniqueness is not important. Multiplying by a prime is a good way of merging multiple fields into one hashCode, but it sounds like you only have one, so it wont make much difference.
Even If employee id is not unique, why its suggested to multiply with odd prime number? why taking any damn integer is not considered good?
If you multiply by an even number what will the lowest bit of the hashCode be? How random/useful is it?
Note: every hashCode() for an Integer is unique, but get the right combination of integer values and when they are reduced to the capacity of a HashMap, they actually map to the same bucket. In this example, the entries appear in the reverse order they were added because every entry mapped to the same bucket.
HashSet<Integer> integers = new HashSet<>();
for (int i = 0; i <= 400; i++)
if ((hash(i) & 0x1f) == 0)
integers.add(i);
HashSet<Integer> integers2 = new HashSet<>();
for (int i = 400; i >= 0; i--)
if ((hash(i) & 0x1f) == 0)
integers2.add(i);
System.out.println(integers);
System.out.println(integers2);
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at 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]