Why Equals (Object o) is equal, hashcode () must be equal

Source: Internet
Author: User

First,int hashcode (); is to support a hash table class such as HashMap, HashTable, and the like, use a hash table class.

There are three contract classes for the int hashcode () method in the Java Object specification :

(1) as long as the information used by the Equals method of the object has not been modified, the Hashcode method must consistently return the same integer, executed multiple times in the same application, and each execution may not The same.

(2) if the Equals method of two objects is thought of, then each object called Hashcode alone must return a number equal.

(3) if the Equals method of the two objects is not equal, The return value of the Hashcode method can be equal, and returning different values to different objects can improve the performance of the hash table.

below we take HashMap As an example to see why such an agreement is to be made.

is a HashMap 's underlying data structure:

image from http://zhangshixi.iteye.com/blog/672697

through the source and above we can know the bottom of the HASHMAP is an array, and each element of the array is a linked list of Entry organizations. Below is the public V put (K key, v value) of HashMap source code for the method (1.7):

We observe the marked two statements, first byHash (Object key)method to get aHashvalue, and then through theindexformethod to locate theHashThe position of the value in the array. Below isHash (Object key)the source code. We can see that it calls theKeyof thehashcode ()function.

source code for int indexfor (int h, int length): static int indexfor (int h, int length) {return H & (LENGTH-1); }


from the above content we know we useHashMapstorage is andKeyof theHashvalue-dependent. IfHashValue is the same , the position of the positioned array is the same (becauseindexforthe return value only andHashvalues and array lengthslengthabout, while the array oflengthonly changes when re-hashing)

from the front we know that each element of the array is Entry The linked list, if every time Hash values are the same, each time you locate the same position in the array, the list is long and the processing time is very long.

and hash key hashcode method related, so we can understand hashcode The third convention, which produces different for different objects. hashcode

Let's take a look at it now . Why if the Equals method of two objects is equal, then each object that calls the Hashcode method alone must return the same return value. First of all, let 's take a look at the source code obtained by HASHMAP:

Public V get (Object key) {if (key = = null) return Getfornullkey ();         entry<k,v> Entry = Getentry (key); return NULL = = entry?    Null:entry.getValue (); }

we can find that it is reversible, or the hash value is obtained by the hash method , and then the position of the element in the array is positioned by the Indexfor method. Think about it if the Equals method of our two objects is equal, and the value of the Hashcode method can be unequal, does that mean that two logically identical objects can be placed in different locations. Does that mean that we find different addresses (objects) by logically equal keys. There is nothing wrong with this, but it is not our goal to achieve HASHMAP. Here's an example of a simple look at what's going on.

public class user{       private long id;        private string name;       private  String address;       private long phone;         @Override        public boolean  Equals (object obj)        {               if (obj == this)                       return true;               if (!  (obj instanceof  user))                      &nbsP;return false;              user  user =  (user)  obj;               return  (User.id == id && user.phone == phone  && name.equals (User.Name)  && address.equals (user.address));        }               public user (Long id, string name, string address, long phone)        {               super ();               this.id = id;               this.name = name;              this.address =  address;              this.phone =  phone;       }        public  long getid ()        {               return id;       }        public void setid (Long id)         {              this.id  = id;       }       public  String getname ()        {               return name;       }        Public void setname (String name)        {               this.name = name;        }       public string getaddress ()        {               return address;       }        public void setaddress (string address)         {              this.address =  address;       }       public  long getphone ()        {               return phone;       }        public void setphone (Long phone)        {               this.phone = phone;        }               public static void main (String[] args)         {              hashmap<user,  String> map = new HashMap<User,String> ();               map.put (New user (1, "Tom", "China", 13888888888L), " Hello world ");   &Nbsp;           system.out.println (Map.get (new  User (1, "Tom", "China", 13888888888L)));             }       }

our intention is to pass User to find Hello World, but not as we wish, right? Why is it? Because we rewrote the equals method of the User , but did not override the Hashcode method, we used the Hashcode method that inherits from the Object class . Because the address is notthe same with new, the value of hashcode is naturally different. So it was positioned to the other position and nothing was found to return null.


Why Equals (Object o) is equal, hashcode () must be 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.