Answer the question
In order to leave comments, you need to log in
Why do I create the same objects but they have different hashcodes?
I create 2 identical instances of a class, but their hashcodes are different, what am I doing wrong?
Indeed, in theory, the hashcodes of identical objects should ALWAYS be the same.
Thanks in advance for your reply!
How I create and output:
What output I get:
Class and its constructor:
What I expected (conditionally):
( https://habrahabr.ru/post/168195/)
Answer the question
In order to leave comments, you need to log in
Because they are two different things. In order for hashCode to return a value bound to the object's attributes, you need to override the hashCode method in the Card class (and at the same time equals, in order to comply with the contract) with a custom hash calculation, otherwise everything will happen according to the doc:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)
Here, the hash code is calculated, roughly speaking, taking into account the address in memory and the amount of memory occupied. Therefore, since they have different addresses, there will be different hash codes. If you want to compare the contents of classes, it will be easier to write your own version of equals and compare by field.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question