Read the article . From it I realized that methods need to be redefined, because, for example, when receiving objects from different sessions they may have the same id, and if we override hashCode() , then they will differ in hash code, right?

One more thing: here , on a similar question, the answer was given: the methods must be overridden for the correct storage of objects in the Hash and Set collections. Again, the question is why (if not redefining is not correct, how is it not correct)? Please explain more clearly.

  • If the object is stored in any collection, then you need to override equal() and hashCode() . If equal() not overridden, then obets are compared by reference. An override of hashCode() is required due to the internal structure of the collection. - jisecayeyo
  • @Igor Gorbunov question then decided your? Helped? Check the answer if it helped, well, to close the question too. - Vladislav Kuznetsov

1 answer 1

for example, when receiving objects from different sessions they may have the same id, and if we override hashCode (), they will differ in hash

It is not necessary if, apart from equal IDs, the other fields are equal, then hashcode will be the same, but read this article better, everything is clearly described https://habrahabr.ru/post/168195/ . And here https://habrahabr.ru/post/128017/ about the use in the hashMap collection.