-1

I’ve read about hash and HashMap coming from here: https://howtodoinjava.com/java/collections/hashmap/design-good-key-for-hashmap/

In particular:

//Depends only on account number
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + accountNumber;  
    return result;
}

Why the hash code is calculated with prime * result + accountNumber and not only from accountNumber

What meaning has the fixed value prime * result? Why not just prime (result value is 1 so prime time 1 is prime)?

Italo
  • 3
  • 1

2 Answers2

1

Code generation uses that in order in the case of multiple fields to have randomness:

result = prime * result + accountNumber;  
result = prime * result + hairColorAsInt; // Biometrics to identify account
result = prime * result + userWeight;  

So indeed unneeded, but here it might serve a purpose: accountNumber should never leak to the outside if possible, hence duplicating it into the hashCode is undesirable. I do not know of any serialisation storing the hashCode, so it is a weak argument.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

Citing this SO answer, a prime number is necessary to ensure all value combinations of fields in an object create distinct and unique hash codes. Yes, this may not be necessary when you only have a single int for fields, but as soon as you want to add any, you would need to change your implementation to the above source; this is of course not desirable, and the solution works in all use cases, so it may as well be used from the beginning.

Austin Schaefer
  • 695
  • 5
  • 19