saitjr
saitjr

Reputation: 159

About isEqual and hash

This question is about the selector isEqual in objc.

I know when object use isEqual, they compared hash, but how to understand the follow code:

NSString *string = [NSString stringWithFormat:@"%d", 1];
NSLog(@"%d", [@"1" hash] == [string hash]); // output 1

I read the hash of object can not be same, why output is 1?

Upvotes: 1

Views: 99

Answers (1)

weston
weston

Reputation: 54781

I know when object use isEqual, they compared hash

That's not correct. isEqual compares the object without using the hash (usually).

I read the hash of object can not be same

Also not correct, hashes must be equal for equal objects and can be the same for in-equal objects. As hash is an int, there are only 2^32 possible values, not enough for it to be unique for each possible object (unless that object is equivalent to 32 bits or less itself).

The only rule about hash is: If [a isEqual:b] is true, then this must also be true: [a hash] == [b hash].

So as your two strings are equal, both "1", then it follows that the hashes should also be equal.

Upvotes: 3

Related Questions