Various fields for equals and hashcode

I agree with the statement from this post. What issues should be considered when overriding equals and hashCode in Java?

Use the same set of fields that you use to calculate equals (), to calculate hashCode ().

But I have some doubts:

  • Is it absolutely necessary to have the same fields?
  • If yes, what should I do if I do not use the same field?
  • Will this affect HashMap performance or HashMap accuracy?
+2
source share
3 answers

Is it absolutely necessary to have the same fields?

Yes, if you do not want surprises.

If yes, what should I do if I do not use the same field?

hashCode , , equals(), equals hashCode.

, , 3 - a, b, c. a b equals(), 3 hashCode(). , 2 , a b , c , -.

HashMap HashMap?

, , , .

+2

. , , -. -, . javadocs:

  • , Java-, hashCode , . .
  • equals (Object), hashCode .
  • equals (java.lang.Object), hashCode . , -.

, 1 -, -, , equals.

1 hashCode, HashMap , equals().

+2

Fields used in the hash code can be a subset of the fields used in equal. He will still abide by this rule: "When a.equals (b), then a.hashCode () should be the same as b.hashCode ().

"

0
source

Source: https://habr.com/ru/post/1685878/


All Articles