java – Using numbers when overriding the hashCode method

Question:

Yes, in Google you can find the article Dealing with hashCode () and equals () , where the rules for overriding hashCode() and equals() are described in a completely accessible language. As a last resort, you can take Bloch with his Java Philosophy and look at these rules there. It's not about that. The rules are clear to me.

What is unclear is:

@Override
public int hashCode() {
    int hash = 37;
    hash = hash * 17 + str1.hashCode();
    hash = hash * 17 + str2.hashCode();
    hash = hash * 17 + num;                      
    return hash;
}

In different examples, some numbers are taken as a basis. In this example, 37 and 17 are taken.
There are a lot of such examples on the Internet, but in each of them the numbers are different. In one example, the following construction was generally encountered:

@Override
public int hashCode() {
    int hash = new Random().nextInt(255);
    hash = hash * 255 + dozer.hashCode();
    hash = hash * 255 + tank.hashCode();              
    return hash;
}

Which completely confused me. How to redefine the hash code correctly?

In this regard, a number of questions:

  1. Do I need to use any numbers at all?

  2. Does it make a difference which number to choose? Or is it some kind of "agreement" within the team during product development?

  3. Are there any restrictions on the choice of the starting number?

  4. Why every time the hash needs to be multiplied by itself (adding hashes of the object's fields is clear to me)?

Answer:

  1. Why are 37 and 17 used? As a rule, a prime number is chosen as the initial value, this is done to reduce the likelihood of a collision.
  2. The meaning of which number to choose, of course, has. If you store your objects in a hash table, then its performance directly depends on the implementation of hashCode ()
  3. see point 1
  4. In order for the hash values ​​to be as different as possible for objects with the same field values. This is how we achieve an even distribution of the keys in the hash table.
Scroll to Top