Here's the example
The question, as I interpret it, is:
Why, given this conceptually correct implementation of
hashCode
andequals
, are two instances of the class not considered equal when added as keys to thisHashMap
?
It's a very specific question where the error lies in incorrectly overloading the equals
method.
The answer here
Hash code does not provide a unique value. Different objects can have the same hashCode().
The function hashCode() is used by Hash* (HashSet, HashMap, ...) to get a hint into which bin an object should be placed. If there are more than one objects in any one bin, all are tested using the equals function.
So even if you did overwrite hashCode() with a constant function, hashing would functionally return correct results. At (high) costs on performance, though.
discusses the general contract of Java's hashCode
method and how it's used in some collections, but I don't read it as attempting to answer the question at all.
I first commented on the answer to explain that it didn't address the problem or answer the question. No edits were made on the question, so I flagged as "Not an answer". The flag was declined.
Maybe I'm misinterpreting the answer, but it doesn't seem like it attempts to answer the question. Note that the content is technically correct, but not very relevant considering that the OP had explained their expectations of hashCode
.
In a more general case, where an answer discusses general computer science concepts or language constructs, but doesn't address the problem in the question, should that answer be considered an answer?