Question

Question: if there are two objects o1 and o2 such that o1.equals(o2), what is java's standard convention about the relationship between o1.hashCode() == o2.hashCode()?

Answer: o1.hashCode() == o2.hashCode()

I don't know why..what i thought was since o1 and o2 are different objects, they shouldn't have the same hashCode. If what the question says were o1 == o2, then I would say they have the same hashCode since both o1 and o2 point to the same object.

Can anyone point out what I did wrong?

Était-ce utile?

La solution 2

Equals and Hashcode always go hand in hand. If o1 == o2, then they point to the same memory and hashcodes are trivially equal. However, one you implement Equals, you always have to make sure that when Equals returns true, Hashcode must return the same value.

Here are the official docs which set out the requirements/standards.

Autres conseils

.equals is used to evaluate the value of an object. When objects are hashed, their numerical values on a systems level are used to produce a hash code (an integer, if you will). If the objects are the exact same (e.g. in terms of attributes), they will have the same numerical sequence and therefore hash to the same value.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top