Mmmh, Let's assume I have a Letter object. This object have a body (String) and a title (also a String). I want to define that two Letter objects are equals if and only if theirs bodies are equals and theirs titles are equals. How do I implement it? I don't understand why I should override #hash in this case? Julien On 26/05/15 20:54, Esteban A. Maringolo wrote:
2015-05-26 15:45 GMT-03:00 Julien Delplanque <julien@tamere.eu>:
The subject of this mail is exactly my question.
I came to this question by looking at Object>>#= message implementation.
""" = anObject "Answer whether the receiver and the argument represent the same object. If = is redefined in any subclass, consider also redefining the message hash."
^self == anObject """
When do we need to redefine #hash message? Whenever you redefine #=.
Is it the right way to implement equality between two objects or is there another message that I should override? #hash, as per the #= suggests.
Hashed collections (Set mainly, but there are others) index and lookup objects by its hash value.
Esteban A. Maringolo
ps: The proper implementation of #hash to avoid collisions (two different objects sharing the same hash) can be plain simple or a little more complex (mathematically challenging).