Hashcode,equals and = = in Java

Source: Internet
Author: User

The Hashcode method returns the hash code value of the object.

The Hashcode () method can be used to improve the efficiency of the search in the map, map will be based on different hashcode () in different locations, map in the search for an object by Hashcode () to find the corresponding position, and then according to Equals () method to determine whether the object at this location is the same as the object that is currently being inserted. If two objects equals equal, but not in an interval, there is no chance to compare, it will be considered a different object.

So, Java for the Eqauls method and the Hashcode method are defined as:

1, if two objects are the same, then their hashcode value must be the same, also tell us to rewrite the Equals method, we must rewrite the Hashcode method;
2. If the hashcode of two objects are the same, they are not necessarily the same

Hashcode () and Equals () are defined in the object class, which is the base class for all Java classes, so all Java classes inherit both methods.

Note that the Hashcode method is preceded by a native modifier, which means that the Hashcode method is implemented by a non-Java language, and the description is a local method, and its implementation is based on the local machine. The specific method is implemented externally, returning the address of the memory object.

1  /**2 * Returns A hash code value for the object. This method is3 * Supported for the benefit of hashtables such as those provided by4 * <CODE>JAVA.UTIL.HASHTABLE</CODE>.5 * <p>6 * The general contract of <code>hashCode</code> are:7 * <ul>8 * <li>whenever It is invoked on the same object more than once during9 * An execution of a Java application, the <tt>hashCode</tt> methodTen * must consistently return the same integer, provided no information One * used in <tt>equals</tt> comparisons on the object is modified. A * This integer need not remain consistent from one execution of - * Application to another execution of the same application. - * <li>if Objects is equal according to the <tt>equals (Object) </tt> the * method, then calling the <code>hashCode</code> method on each of - * The objects must produce the same integer result. - * <li>it is <em>not</em> required that if the objects is unequal - * According to the {@linkjava.lang.object#equals (java.lang.Object)} + * method, then calling the <tt>hashCode</tt> method on each of the - * objects must produce distinct integer results. However, the + * Programmer should is aware that producing distinct integer results A * For unequal objects may improve the performance of hashtables. at * </ul> - * <p> - * As much as is reasonably practical, the Hashcode method defined by - * Class <tt>Object</tt> does return distinct integers for distinct - * objects. (This was typically implemented by converting the internal - * Address of the object into a integer, but this implementation in * Technique is isn't required by the - * Java<font size= "-2" ><sup>TM</sup></font> programming language.) to      * +      * @returna hash code value for the This object. -      * @seejava.lang.object#equals (java.lang.Object) the      * @seejava.util.Hashtable *      */ $      Public native intHashcode ();
View Code

These two methods can be overridden in a Java class, and the following are implementations of the two classes in the String class.

1 /**2 * Compares this string to the specified object. The result is {@code3 * true} if and only if the argument are not {@codenull} and is a {@code4 * String} object that represents the same sequence of characters as this5 * object.6      *7      * @paramAnObject8 * The object to compare this {@codeString} against9      *Ten      * @return  {@codetrue} If the given object represents a {@codeString} One * Equivalent to this string, {@codefalse} otherwise A      * -      * @see#compareTo (String) -      * @see#equalsIgnoreCase (String) the      */ -      Public Booleanequals (Object anobject) { -     if( This==anobject) { -         return true; +     } -     if(AnObjectinstanceofString) { +String anotherstring =(String) anobject; A         intn =count; at         if(n = =anotherstring.count) { -         CharV1[] =value; -         CharV2[] =Anotherstring.value; -         inti =offset; -         intj =Anotherstring.offset; -          while(n--! = 0) { in             if(v1[i++]! = v2[j++]) -             return false; to         } +         return true; -         } the     } *     return false; $}
View Code
1 /**2 * Returns A hash code for this string. The hash code for a3 * <code>String</code> object is computed as4 * <blockquote><pre>5 * s[0]*31^ (n-1) + s[1]*31^ (n-2) + ... + s[n-1]6 * </pre></blockquote>7 * Using <code>int</code> arithmetic, where <code>s[i]</code> is the8 * <i>i</i>th character of the string, <code>n</code> is the length of9 * The string, and <code>^</code> indicates exponentiation.Ten * (the hash value of the empty string is zero.) One      * A      * @returna hash code value for the This object. -      */ -      Public inthashcode () { the     inth =Hash; -         intLen =count; -     if(h = = 0 && len > 0) { -         intOff =offset; +         CharVal[] =value; -  +              for(inti = 0; i < Len; i++) { AH = 31*h + val[off++]; at             } -hash =h; -         } -         returnh; -}
View Code

equals in the String class is a content-based comparison, not an address-based comparison.

The Java language requires the following for Equals (), which are required to be followed:
• Symmetry: If X.equals (y) returns "true", then Y.equals (x) should also return "true".
• Reflectivity: X.equals (x) must return "true".
• Analogies: If X.equals (y) returns "true" and Y.equals (z) returns "true", then Z.equals (x) should also return "true".
• Consistency: If x.equals (y) returns "true", as long as the X and Y contents remain constant, the return is "true" no matter how many times you repeat X.equals (y).
• In any case, x.equals (NULL) will always return "false", and X.equals (and X objects of different types) will always return "false".
These five points are the criteria that must be adhered to when overriding the Equals () method, and if the violation will result in unexpected results, please be sure to follow.

java = =, Equals (), hashcode () are related to the comparison of objects, in Java, what is the usefulness of these three, that is, why in Java need to design these three kinds of object comparison method?

  1. about = =

    = = is easy to understand. Java design Java is to compare two objects is not the same object.

    For reference variables, the two reference variables refer to the same object when compared, that is, the address of the object stored in two references is not the same.

    For the basic data type, the comparison is two data is not equal, no ambiguity.

    Because there is no method for the base data type, there is no problem with equal () and hashcode (), and the following discussion is for reference types.

  2. About Equals ()

    Why does Java design the Equals () method?

    = = Compared to whether two objects are the same object, this does not meet many requirements. Sometimes when two objects are not = =, we still think that the two are "equal", for example, for a string object, when the string sequence of two objects is constant, we think they are "equal". For such a requirement, equals () is required to implement. For classes with objects of this kind, overriding their equals () method allows specific "equality" logic to be defined on its own.

    Places to be aware of

    The default implementation of Equals () in object is to compare two objects that are not = = and that their and = = effects are the same.

    Some of the classes provided by Java have overridden the Equals () method. Write your own class, and if you need to implement your own "equal" logic, you need to rewrite the Equals () method.

  3. About Hashcode ()

    Why is the Hashcode () method designed?

    The Hashcode () method returns a value that we call hashcode. As you can see from the name of the method, the purpose is to generate a hash code. The main purpose of hash code is to hash the object as a key input, it is easy to infer that we need each object hash code as much as possible, in order to ensure the hash of the access performance. In fact, the default implementation provided by the object class does guarantee that each object's hash code is different (a hash code is returned by a particular algorithm based on the object's memory address).

    Analysis to this place, seemingly no problem, the role of the three is clear, as if they have nothing to do with. In the Java specification, the Hashcode () method and the Equals () method do not have a relationship.

    But!!!!!!!! There is a problem.

    The problem is as follows: For Class HashSet, HashMap, and hash related classes (take HashSet as an example), hash the object by hash algorithm. For HashSet, the process of depositing objects is: According to the object's hash code, through the hash algorithm, find where the object should be stored, if the location is empty, then the object is stored in that position, if the location is not empty, then use Equals () to compare the location of the object and the object to be entered, If two are equal, they are no longer inserted, and if not equal, the object is inserted into another location based on the hash conflict resolution algorithm.

    Java rules for hashset to judge whether the duplicate object is done by the Equals () method, which requires that the Equals () method of the two objects equal, the hash code must be equal (that is, hashcode () returns the same value). Assuming that the Equals () method of the two objects is equal, the hash code is unequal, and two objects equal to equals () are inserted into the hashset, which is not allowed. So we have a little bit of a conclusion:

    Conclusion: for two objects equal to Equals (), their hashcode () must return a value equal

    Through the above analysis, there is no objection to this conclusion. In combination with the requirements of the previous hash code to be as different as possible, now becomes equal to equals () the object hash code must be equal, and for Equals () different objects to try to do the hash code is different. So how can we guarantee this?

  4. Rewrite Hashcode ()

    First, how to ensure that the "equals () equal to the object hash code must be equal."

    The comparison of objects in the Equals () method is done by comparing all or some of the fields in the object, which are recorded as collection A, and if we calculate the hash code, just select a partial field or all of the fields from set a to complete, because the input is the same, regardless of the algorithm, The output must be the same (random function is called in the method). It's a feast for the hungry! )。 This design ensures that the first requirement is met.

    Second, for Equals () different objects to try to do the hash code is different.

    The guarantee for this is to design a good algorithm that allows different inputs to produce different outputs as much as possible.

    Here is a detailed description of how to design this algorithm. This algorithm has a ready-made reference, the specific steps of the algorithm are:

    [1] A non-0 constant value (the general number of prime), such as 17, is stored in the int variable result;

    [2] For each key domain F in the object (refers to each domain considered in the Equals method):

    [2.1]boolean type, calculation (f 0:1);

    [2.2]byte,char,short type, calculation (int) F;

    [2.3]long type, calculation (int) (f ^ (f>>>32));

    [2.4]float type, calculated float.floattointbits (afloat);

    [2.5]double type, calculated Double.doubletolongbits (adouble) Gets a long, then executes [2.3];

    [2.6] Object reference, recursive invocation of its Hashcode method;

    [2.7] An array field that invokes its Hashcode method on each of these elements.

    [3] The above computed hash code is saved to the INT variable C, and then executed Result=37*result+c;

    [4] returns result.

    In fact, the idea is: first go to a base, and then for Equals () in the consideration of each domain, first converted to an integer, then execute result=37*result+c;

Reference

http://blog.csdn.net/naughty610/article/details/7027583

http://www.oschina.net/question/82993_75533

http://crd1991.iteye.com/blog/1473108

Http://jingyan.baidu.com/article/ff41162582507512e5823763.html

Hashcode,equals and = = in Java

Related Article

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.