Overwrite the Equals method why you need to overwrite the Hashcode method

Source: Internet
Author: User

Overwrite the Equals method must overwrite the Hashcode method, which is explained repeatedly on the JDK API, but why do you do this? What is the relationship between the two methods?

voidTest () {//instance of the person class as the key of the mapMap<person, object> map =NewHashmap<person, object>(); Map.put (NewPerson ("Zhang San"),NewObject ()); //instance of the person class as an element of listlist<person> list = newarraylist<person>() List.add (NewPerson ("Zhang San")); //whether the list contains    BooleanB1 = List.contains (NewPerson ("Zhang San")); //does the map contain    BooleanB2 = Map.containskey (NewPerson ("Zhang San")); System.out.println (B1+ "|" +b2);}

Person class:

 Public classPerson {PrivateString name; PrivateString age;  PublicPerson (String name) {setName (name); }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getage () {returnAge ; }     Public voidsetage (String age) { This. Age =Age ; } @Override Public Booleanequals (Object o) {/** The use of getclass is to prevent subclasses from being judged as the parent class case * For example: The person in the override Equals method {return name.equals (p.getname);}         * Subclass employee Inherits person, at this time the Euqals method in subclass Super.equlas (p);         * If the instanceof keyword is used, because the employee is a subclass of person, it returns true * further invocation of equals returns True, so it is not reasonable to think that people and employee are the same */        if(O! =NULL&& O.getclass () = = This. GetClass ()) {Person P=(person) o; if(P.getname () = =NULL&& This. Name = =NULL)                return false; return  This. Name.equals (P.getname ()); }        return false; }}

Let's first look at the equals of the B1,person class, no longer judging whether the two addresses are equal, but rather the equality of two objects based on the name of the person, so no matter how many objects are produced by our new Man ("Zhang San"), they are equal. Put the "Zhang San" object in the list, and then check whether the list contains, the result must be true.

Then see B2, we put Zhang San this object as a map of the key (key), put in the object is Zhang San, check the object or Zhang San, it should be the same as the results of the list, but unfortunately, the result is false. What is the reason?

The reason is that the underlying processing mechanism of HASHMAP is to save the map entry (map Entry) in an array, the key of which is the processing mechanism of the array subscript: Based on the return value of the incoming element hashcode method to determine its array subscript, if the array location has a map entry, and equal to the incoming key value is not processed, if not equal is overwritten; if there is no entry for the array position, it is inserted and added to the list of map entries. Similarly, checking whether a key exists is also based on the hash code to determine the location, and then traverse the lookup key value.

And then delve into it, what value does the Hashcode method of the object element return? It is a hash code of an object, generated by the local method of the object class, ensuring that each object has a hash code (which is also the basic requirement of the hashing algorithm: any input k, through an algorithm f (k), convert it to a non-reversible output, for two inputs K1 and K2, if K1=K2 is required, then must f ( K1) =f (K2), but also allows k1≠k2,f (K1) =f (K2) to exist.

Back to our example, since we did not rewrite the Hashcode method, the return value (that is, the hash code) of the two-sheet three-object Hashcode method is definitely not the same, and the corresponding map entry is not found in the HashMap array, so it returns false.

The problem is clear, the modification is very simple, rewrite the Hashcode method, the code is as follows:

 Public int hashcode () {     /// where Hashcodebuilder is a hash code generation tool under the Org.apache.commons.lang.builder package,      // easy to use, you can integrate directly into the project.      returnnew  hashcodebuilder (). Append (name). Tohashcode ();}

The Hashcodebuilder is a hash code generation tool under the Org.apache.commons.lang.builder package, which is very convenient to use, and you can integrate directly into your project. (Why not write the Hashcode method directly?) Because the hash code generation has many kinds of algorithms, its own trouble, the matter is many, so adopt take doctrine is the best method. )

Overwrite the Equals method why you need to overwrite the Hashcode method

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.