How objects of a custom type are judged equal

Source: Internet
Author: User

There are two key methods for determining equivalence in the NSObject protocol:

-(BOOL) IsEqual: (ID)object;  

The default implementation of the NSObject class for both methods is that the two objects are equal only if and only if their pointer value (pointer value) is exactly equal. If the "IsEqual:" method determines that two objects are equal, the hash method must also return the same value. However, if the hash method of two objects returns the same value, then the "IsEqual:" method may not be considered equal.

For example, there is the following class:

@interface Eocperson:nsobject   *firstName;   *LastName;  @property (nonatomic, assign) Nsuinteger age;   @end

We think that if all the fields of the two Eocperson are equal, then the two objects are equal. So the "IsEqual:" Method can be written as:

-(BOOL) IsEqual: (ID)Object {      if(Self = =Object)returnYES; if([Selfclass] != [Object class])returnNO; Eocperson*otherperson = (eocperson*)Object; if(![_FirstName isEqualToString:otherPerson.firstName])returnNO; if(![_lastname isEqualToString:otherPerson.lastName])returnNO; if(_age! =otherperson.age)returnNO; returnYES; } 

First, directly determine whether the two pointers are equal. If they are equal, they all point to the same object, so the objects under test must also be equal. Next, compare the classes to which the two objects belong. If you do not belong to the same class, the two objects are not equal. The Eocperson object is certainly not equal to the Eocdog object. However, sometimes we may think that a Eocperson instance can be equal to its subclasses (such as Eocsmithperson) instances. This kind of problem is often encountered in the inheritance system (inheritance hierarchy) when judging equivalence. So take this into account when implementing the "IsEqual:" approach. Finally, check that each property is equal. As long as there are unequal attributes, two objects are judged to be unequal, otherwise two objects are equal.

The next step is to implement the hash method. Recall that, according to the equivalence Convention: If two objects are equal, their hash code (hash) is also equal, but the two hash code objects are not necessarily equal. This is the key to the ability to correctly overwrite the "isequal:" approach. The following is perfectly possible:

- (Nsuinteger) hash {      return1337;  

However, if this is the case, the use of this object in collection will produce performance problems because collection will index the hash of the object when retrieving the hash table. If a collection is implemented with set, then set may divide the object into different arrays based on the hash code. When you add a new object to a set, you find the array associated with it based on its hash code, examining each of the elements in turn to see if the objects already in the array are equal to the new objects that will be added. If it is equal, it means that the object to be added is already in the set. It is to be expected that if each object returns the same hash code, then if there are already 1?000?000 objects in the set, then if you continue to add objects to it, you need to scan the 1?000?000 objects all over again.

The hash method can also be implemented like this:

- (Nsuinteger) hash {      *stringtohash =          [nsstringstringwithformat:@ "%@:%@:%i  ",              _firstname, _lastname, _age];       return [Stringtohash hash];  

The method used this time is to cram the attributes in the NSString object into another string, and then let the hash method return the hash code of the string. Doing so conforms to the Convention because two equal Eocperson objects always return the same hash code. However, this will also burden the overhead of creating strings, so it is slower than returning a single value. When you add this object to the collection, you also have a performance problem, because the hash code must be computed first to add it.

Let's look at the last way to calculate the hash code:

- (Nsuinteger) hash {      = [_firstname hash];       = [_lastname hash];       = _age;       return firstnamehash ^ Lastnamehash ^ Agehash;  

This approach is both highly efficient and allows the generated hash code to be at least within a certain range, rather than repeating too frequently. Of course, the hash code generated by this algorithm will still collide (collision), but at least the hash code can be guaranteed to have a number of possible values. When writing a hash method, you should experiment with the current object in order to choose between reducing the frequency of collisions and reducing the complexity of the operation.

How objects of a custom type are judged equal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.