Yes, in Google you can find the article. We deal with hashCode () and equals () , where the rules for overriding hashCode() and equals() are described in a completely accessible language. In extreme cases, you can take the same Bloch with its Java philosophy and see these rules there. It's not about that. The rules are clear to me.

This is not clear:

 @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 encountered:

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

What totally confused me. How to correctly redefine the hash code?

In this regard, a number of questions:

  1. Should I use any numbers at all?

  2. Does it matter what number to choose? Or is it some kind of "agreement" within the team when developing a product?

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

  4. Why does the hash need to be multiplied by itself each time (I understand the addition of the object field hashes to me)?

    2 answers 2

    1. Why use 37 and 17? As a rule, a prime number is chosen as the initial value; this is done to reduce the likelihood of a collision.
    2. Meaning what number to choose, of course, has. If you store your objects in a hash table, its performance directly depends on the implementation of hashCode ()
    3. see point 1
    4. In order for hash values ​​to be as different as possible for objects with identical field values. With this we achieve uniform distribution of keys in the hash table.
    • 2
      It is possible, by the way, to note that for constructions int hash = new Random().nextInt(255); relies shooting. - Regent
    • @Regent fully agrees with you :) - Artem Konovalov

    Here in this article such numbers are mentioned - Notes on the implementation of hashCode () in Java .
    It is not necessary to use any "magic" numbers, most likely in the examples this is done to reduce collisions.
    For example, the Integer class hashCode simply returns a number that was written to a variable, i.e. inside there is no multiplication by any number.

    • Not a bad article, but the algorithm is proved in the vein of "Suppose," "We assume," etc. Especially caught my eye. То есть мы не будем работать с отрицательными значениями. And overflow of digit capacity? If the hash is greater than 2 ^ 32, it will become negative. stackoverflow.com/questions/9249983/… - like here. So, sorry - not very convincing. - Sergey Shustikov