NSObject Protocol Reference says “If two objects are equal, they must have the same hash value.”
Why must?
What could be the problem with two equal objects not having same hash value?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here is a simplified description of how a hash table works. NSSet is a hash table.
The basic structure
Allocate an NSArray of N NSMutableArrays. Let’s call the outer array “table” and the inner arrays “lists”. This structure is our hash table.
How inserting works
To insert an object, call ‘hash’ on it. This gives us a number. Truncate the number to be between 0 and (N – 1). Treat that result as an index in table. Go to the mutable array at that slot (list), and see if ‘object’ is already in the list, if not add it. If so, nothing to do.
How lookup works
To see if a value is in the hash table, call hash on it. This gives us a number. Truncate the number to be between 0 and (N – 1). Treat that result as an index in table. Go to the mutable array at that slot (list), and see if ‘object’ is already in the list. If it’s there, the table contains the object, otherwise it doesn’t.
Why do equal objects have to have equal hash values?
The hash code is used to find which list to search. If two objects are conceptually equal but have different hash values, then when we go to do the look up above in the outer table we won’t find the object in the expected list since our objects will resolve to two different lists.