equals and hashCode: Is Objects.hash method broken?

后端 未结 4 1808
有刺的猬
有刺的猬 2021-01-03 04:51

I am using Java 7, and I have the following class below. I implemented equals and hashCode correctly, but the problem is that equals r

4条回答
  •  生来不讨喜
    2021-01-03 05:36

    Actually, you happened to trigger pure coincidence. :)

    Objects.hash happens to be implemented by successively adding the hash code of each given object and then multiplying the result by 31, while String.hashCode does the same with each of its characters. By coincidence, the differences in the "English" strings you used occur at exactly one offset more from the end of the string as the same difference in the "Chamorro" string, so everything cancels out perfectly. Congratulations!

    Try with other strings, and you'll probably find that it works as expected. As others have already pointed out, this effect is not actually wrong, strictly speaking, since hash codes may correctly collide even if the objects they represent are unequal. If anything, it might be worthwhile trying to find a more efficient hash, but I hardly think it should be necessary in realistic situations.

提交回复
热议问题