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