In today's Codeforces Round (#763) problem B, I tried finding a pair
object in a HashSet. Even after overriding equals() and hashcode() methods, I still ended up with WA
on test 4. Here is the link to my solutions:
1) WA Submission using HashSet
2) Working Solution using 2D matrix
Please let me know of a good fix for this.
Use
Integer.equals
instead of==
in yourpair.equals
, otherwise you getfalse
when comparing two objects with the same value but different references. Btw, same bug in thepair.compareTo
method.Check this AC solution: https://mirror.codeforces.com/contest/1623/submission/140959789
btw,
Integer
is pretty slow compared toint
. So if possible (like in this case), it is better to useint
.So if I use
int
, how will myhashcode()
work?Like this: https://mirror.codeforces.com/contest/1623/submission/140960231
Another hint: if you use JetBrains IDEA, in most cases you can use auto-generated equals and hashCode methods. It is just a couple of clicks: https://www.jetbrains.com/help/idea/generating-code.html#generate-equals-hashcode
I don't get how the 13*x + y is working can you please explain.
Does this mean that a pair — 5, 14 and a pair 6, 1 will have the same hashcode inside the hashset?
Yeah, two unrelated pairs could have the same hashcode. This is why you also need to override equals(), because two things with the same hash might have different values.