I
I
Indeoo2017-06-24 20:15:39
Java
Indeoo, 2017-06-24 20:15:39

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:
e7897ffca83c4c3dac83e66b180d808b.png
What output I get:
cec601243862470d84b4e67311a02a67.png
Class and its constructor:
9bcdae2f7e294f8ea7dbb4690a5be03b.png
What I expected (conditionally):
38f6ddd128c0371f0586d157a562b1ae.png
( https://habrahabr.ru/post/168195/)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
roswell, 2017-06-24
@roswell

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.)

K
Konstantin Stepanov, 2017-06-24
@koronabora

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.

N
Nikita, 2017-06-24
@jkotkot

So they are not the same :) You can check for yourself that they are not equals

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question