1

Whenever I override hashcode() using eclipse 'source' menu it generates following code in the class

final int prime = 31;
int result = 1;
result = prime * result + ((fieldName1== null) ? 0 : fieldName1.hashCode());
result = prime * result + ((fieldName2== null) ? 0 : fieldName2.hashCode());

Could anyone please explain why it is doing all this calculation(multiplication and then addition), why it is not returning simply

fieldName.hashCode();
or
fieldName2.hashCode();

?

Just_another_developer
  • 5,737
  • 12
  • 50
  • 83

3 Answers3

0

Multiplying reduces collisions.

Please read Joshua Bloch

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

It is explained here.

Basically you use primes in multiplication to have a better distribution of the hash values. Then HashSet and HashMap work better because they distibute according to the hash value. And badly distributed hash values lead to many collisions.

Community
  • 1
  • 1
Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48
0

why it is not returning simply fieldName.hashCode(); or fieldName2.hashCode();

To understand why, you must also examine the implementation of equals() and understand the constraints placed on the hashCode() implementation.

  1. A hashCode() implementation must return equal values for objects that compare as equal: if x.equals(y) then x.hashCode() == y.hashCode().

  2. A good hashCode() implementation should rarely return the same hash code for objects that do not compare as equal: if !x.equals(y) then often x.hashCode() != y.hashCode().

  3. The equals() implementation that Eclipse generated examines both fileName1 and filename2. If either are different for two objects, the method will consider them the two objects to be not equivalent.

  4. Therefore a corresponding good hashCode() implementation should produce different hash code values if either fileName1 or fileName2 are different.

  5. Therefore a corresponding good hashCode() implementation should use fileName1.hashCode() and fileName2.hashCode().

Raedwald
  • 46,613
  • 43
  • 151
  • 237