The role of Hashcode in Java

Source: Internet
Author: User

Hash table This data structure presumably most people are not unfamiliar, and in many places will use hash tables to improve the search efficiency. There is a method in the object class of Java: According to the public native int hashCode(); declaration of this method, the method returns a numeric value of type int and is a local method, so no concrete implementation is given in the object class.

I. The role of the Hashcode method

The main purpose of the Hashcode method is to work properly with a hash-based collection that includes HashSet, HashMap, and Hashtable.

Why do you say that? Consider the case of how to determine if an object already exists in the collection when it is inserted into the collection. (Note: Duplicate elements in the collection are not allowed to exist)

Perhaps most people would have thought of calling the Equals method to make comparisons on a case by case basis. However, if there are already 10,000 or more data in the collection, if the Equals method is used to compare each other, efficiency must be a problem. At this point the function of the Hashcode method is reflected, when the collection to add a new object, the first call the object's Hashcode method, to get the corresponding hashcode value, In fact, in the implementation of HASHMAP will use a table to save the hashcode value of the object that has been stored in, if the table does not have the hashcode value, it can be stored directly in, no further comparison, if there is a hashcode value, The Equals method that calls it is compared with the new element, the same is not saved, and the other addresses are hashed, so there is a conflict resolution problem. In this way, the number of actual calls to the Equals method is greatly reduced, saying that thehashcode method in Java is to map the object-related information (such as the object's storage address, the object's field, etc.) to a value according to certain rules, which is called the hash value . The following code is a concrete implementation of the Put method in Java.util.HashMap:

 Publicv put (K key, V value) {if(Key = =NULL)            returnPutfornullkey (value); inthash =Hash (Key.hashcode ()); inti =indexfor (hash, table.length);  for(entry<k,v> e = table[i]; E! =NULL; E =e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) {V OldValue=E.value; E.value=value; E.recordaccess ( This); returnOldValue; }} Modcount++;        AddEntry (hash, key, value, I); return NULL; }

The Put method is used to add a new element to the HashMap, and from the concrete implementation of the Put method, the Hashcode method is called to get the hashcode value of the element, and then see if the hashcode value exists in the table. If present, call the Equals method to re-determine if the element exists, update the value if it exists, or add the new element to HashMap. As can be seen here, the Hashcode method exists to reduce the number of calls to the Equals method, thus improving program efficiency.

If the hash table of the data structure of the friend is not clear, you can refer to http://www.cnblogs.com/lchzls/p/6714079.html

Some friends mistakenly think that by default, Hashcode returns the object's storage address, in fact, this view is not comprehensive, indeed some JVMs are implemented to directly return the object's storage address, but most of the time is not the case, can only say that the storage address has a certain association.

Is it possible to determine the equality of two objects directly based on the hashcode value? It is certainly not possible, because different objects may generate the same hashcode value. Although it is not possible to determine whether two objects are equal according to the Hashcode value, two objects can be judged directly from the hashcode value, and if the hashcode value of two objects is unequal, it must be two different objects. If you want to determine whether two objects are truly equal, you must pass the Equals method.

In other words, for two objects,

1. If the result of calling the Equals method is true, the hashcode value of the two objects must be equal;

2. If the Equals method results in False, the hashcode value of the two objects may not be different;

3. If the hashcode value of two objects is unequal, the result of the Equals method must be false;

4. If the hashcode value of the two objects is equal, the result of the Equals method is unknown.

Two. Equals Method and Hashcode method

Hashcode is used for lookup purposes, while equals is used to compare two objects for equality

In some cases, the programmer needs to rewrite the Equals method when designing a class, such as the string class, but it is important to note that the Hashcode method must be overridden while overriding the Equals method . Why do you say that?

Let's look at an example:

 PackageCom.cxh.test1;ImportJava.util.HashMap;ImportJava.util.HashSet;ImportJava.util.Set;classpeople{PrivateString name; Private intAge ;  PublicPeople (String name,intAge ) {         This. Name =name;  This. Age =Age ; }            Public voidSetage (intAge ) {         This. Age =Age ; } @Override Public Booleanequals (Object obj) {//TODO auto-generated Method Stub        return  This. Name.equals (((people) obj). Name) && This. age==((people) obj). Age; }}  Public classMain { Public Static voidMain (string[] args) {people P1=NewPeople ("Jack", 12);                     System.out.println (P1.hashcode ()); HashMap<people, integer> HashMap =NewHashmap<people, integer>(); Hashmap.put (P1,1); System.out.println (Hashmap.get (NewPeople ("Jack", 12))); }}

Here I only rewrite the Equals method, and say if the two people object, if its name and age are equal, it is considered the same person.

The intent of this code is to think that the output of this code is "1", but in fact it outputs "null". Why is it? The reason is to rewrite the Equals method while forgetting to rewrite the Hashcode method.

Although the two objects with the same logical name and age are judged to be equal objects by overriding the Equals method (similar to the String Class), it is known by default that the Hashcode method maps the storage address of an object. It is not surprising that the output of the above code is "null". The reason is simple, P1 points to the object and

System.out.println (Hashmap.get ("Jack", 12)), the new people in this sentence ("Jack", 12) produces two objects whose storage address must be different.

The following is a concrete implementation of the Get method for HashMap:

 PublicV get (Object key) {if(Key = =NULL)            returnGetfornullkey (); inthash =Hash (Key.hashcode ());  for(Entry<k,v> e =table[indexfor (hash, table.length)]; E!=NULL; E=e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) returnE.value; }        return NULL; }

So when HashMap get operations, because the resulting hashcdoe value is different (note that the above code may in some cases get the same hashcode value, but this probability is relatively small, Because although the storage address of two objects is different, it is possible to get the same hashcode value), so the for loop in the Get method does not execute and returns null directly.

So if you want the above code to output as "1", it is very simple to rewrite the Hashcode method so that the Equals method and the Hashcode method always logically maintain consistency.

 PackageCom.cxh.test1;ImportJava.util.HashMap;ImportJava.util.HashSet;ImportJava.util.Set; classpeople{PrivateString name; Private intAge ;  PublicPeople (String name,intAge ) {         This. Name =name;  This. Age =Age ; }            Public voidSetage (intAge ) {         This. Age =Age ; } @Override Public inthashcode () {//TODO auto-generated Method Stub        returnName.hashcode () *37+Age ; } @Override Public Booleanequals (Object obj) {//TODO auto-generated Method Stub        return  This. Name.equals (((people) obj). Name) && This. age==((people) obj). Age; }}  Public classMain { Public Static voidMain (string[] args) {people P1=NewPeople ("Jack", 12);                     System.out.println (P1.hashcode ()); HashMap<people, integer> HashMap =NewHashmap<people, integer>(); Hashmap.put (P1,1); System.out.println (Hashmap.get (NewPeople ("Jack", 12))); }}

This passage is excerpted from the effective Java book:

    • The Hashcode method must consistently return the same integer as long as the information used for the comparison operation of the Equals method is not modified during program execution, and the same object is called multiple times.
    • If two objects are equal according to the Equals method, then the Hashcode method that calls two objects must return the same integer result.
    • If two objects are unequal according to the Equals method, the Hashcode method does not necessarily return different integers.

Here's an example:

 PackageCom.cxh.test1;ImportJava.util.HashMap;ImportJava.util.HashSet;ImportJava.util.Set; classpeople{PrivateString name; Private intAge ;  PublicPeople (String name,intAge ) {         This. Name =name;  This. Age =Age ; }            Public voidSetage (intAge ) {         This. Age =Age ; } @Override Public inthashcode () {//TODO auto-generated Method Stub        returnName.hashcode () *37+Age ; } @Override Public Booleanequals (Object obj) {//TODO auto-generated Method Stub        return  This. Name.equals (((people) obj). Name) && This. age==((people) obj). Age; }}  Public classMain { Public Static voidMain (string[] args) {people P1=NewPeople ("Jack", 12);                 System.out.println (P1.hashcode ()); HashMap<people, integer> HashMap =NewHashmap<people, integer>(); Hashmap.put (P1,1); P1.setage (13);    System.out.println (Hashmap.get (p1)); }}

The result of this code output is "null", presumably for the reason that everyone should be clear.

The role of Hashcode in Java

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.