= = in Java, the difference and connection between equals and Hashcode

Source: Internet
Author: User
Tags instance method

I. Overview

1. concept

    • = =: the operator generates a Boolean result that calculates the relationship between the operands ' values
    • equals: An instance method of object that compares the content of two objects
    • hashcode: Object's Native method , which gets the hash value of the object used to determine the index position of the object in the hash table, which is actually an int type integer
second, relational operator = =

1, the value of the operand

    • Basic Data type variables

      There are eight basic data types in Java:

      Float type: float (4 byte), double (8 Byte)

      Integer: byte (1 byte), short (2 byte), int (4 byte), long (8 Byte)

      Character Type: Char (2 Byte)

      Boolean: Boolean (JVM specification does not explicitly specify the amount of space it occupies, only the literal value "true" and "false" is Specified)

        for variables of these eight basic data types, variables directly store "value". therefore, when using the relational operator = = To compare, The comparison is the "value" itself. Note that both floating-point and integral types are signed (the highest bits are used only for positive and negative, do not participate in the calculation "in the case of byte, which ranges from -2^7 ~ 2^7-1,-0 to 128"), and char is an unsigned type (all bits participate in the calculation, So the char type takes a value range of 0~2^16-1).

    • Reference type variable
      In java, a variable of a reference type stores not the value itself, but the address of the object associated with it in memory . such as the following line of code,
    String str1;

This statement declares a variable of a reference type, at which point it is not associated with any Object.
instead, a new object is generated and the object is bound to the Str1:

new String("hello");

So str1 points to this object, where the reference variable STR1 stores the address of the object it points to in memory, not the "value" itself, that is, the string "hello" that is not stored directly. The references in this are very similar to the pointers in C + +.

2. Summary

therefore, for the relational operator = =:

    • If the type of the operand is the base data type , the relational operator determines whether the values of the operands on the left and right sides are equal
    • If the type of the operand is a reference data type , the relational operator determines whether the memory address of the left and right operands is the Same. That is , if you return true at this point, the operator must be the same object.
third, the Equals method

1. source
The Equals method is an instance method in the base class object, so it will be available to all classes that inherit from Object.
  
Declaration in Object:

    publicbooleanequals(Object obj) {}

2. The role of the Equals method
 purpose: Determine whether the content of two objects is the same

To more intuitively understand the role of the equals method, we first look at the implementation of the Equals method in the object class.

  publicbooleanequals(Object obj) {    return (this == obj);  }

obviously, in the object class, the Equals method is used to compare the Two-object references for equality, that is, to point to the same object.

But as we all know, the following code output is True:

publicclass Main {    publicstaticvoidmain(String[] args) {        new String("hello");        new String("hello");        System.out.println(str1.equals(str2));    }}

It turns out that the String class overrides the Equals method:

 public Boolean equals(Object Anobject) {//method Signature is consistent with the object class    if( this= = Anobject) {//to Determine if the reference is the same (whether it is the same object),        return true; }if(anobjectinstanceofString) {//re-determine The type is consistent,        ///final judgment content is Consistent.String anotherstring = (string) anobject;intn = count;if(n = = Anotherstring.count) {Charv1[] = value;Charv2[] = anotherstring.value;inti = offset;intj = anotherstring.offset; while(n--! =0) {if(v1[i++]! = V2[j++])return false; }return true; }    }return false;}

What is the internal implementation of the method used for string comparisons? The answer to the question Is:

With the Equals method, an internal implementation is divided into three steps:

    • first, Compare whether the reference is the same (whether it is the same Object),
    • Again to determine whether the type is consistent (is the same Type),
    • The final comparison of the content is consistent

This is true of all implementations of the Equals method of all built-in classes in Java, especially wrapper classes such as Integer,double.

3. The overriding principle of equals

The object content comparison is the true purpose of designing equals (), and the Java language requires equals () as follows, which must be followed when overriding the Method:

    • symmetry : If x.equals (y) returns "true", then Y.equals (x) should also return "true";

    • reflexivity : x.equals (x) must return is "true";

    • analogy : 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 is "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);

    • symmetry : If x.equals (y) returns "true", then Y.equals (x) should also return "true".

    • In any case,x.equals (null) "should Use the relational comparer = =" and always return "false"; x.equals (and x objects of different types) will always return "false"

4. Summary
therefore, for the Equals method:

    • It is intended to compare the content of two objects with the same
    • When necessary, we need to rewrite this method to avoid breaking the original intention and to follow the above principles
Iv. Methods of Hashcode

1, the source of Hashcode
The Hashcode method is the instance native method in the base class object, so there is this method for all classes that inherit from Object.
  
The declaration in the object class (the native method implies that these methods have an implementation, but does not provide the implementation body, because the implementation body is implemented outside of the Non-java language):

     publicnativeinthashCode();

2. Hash Related concepts
Let's take a look at the hash table first:

    • concept: Hash is the arbitrary length of the input (also known as pre-mapping, pre-image), through the hashing algorithm, converted to a fixed-length output ( int ), The output is the hash Value. This conversion is a compression map , which means that the space for the hash value is usually much smaller than the input space. The different inputs may be hashed to the same output, making it impossible to uniquely determine the input value from the hash Value. Simply put, it is a function that compresses messages of any length to a message digest of a fixed length.

    • Apps – Data structures: arrays are characterized by easy addressing, insertion and deletion difficulties, and linked lists that are difficult to address, easy to insert and Delete. Can we combine the characteristics of both to make a data structure that is easy to address, insert and delete?                        The answer is yes, this is the hash table we are going to mention, the hash table has a number of different implementations, and i'll explain the most commonly used method-the Zipper method , which we can understand as "array of linked lists" ,


      Figure 1 Example of a hash

      The left side of the

      is obviously a set of arrays, and each member of the array is a linked List. All elements contained in the data structure contain a pointer to the link between elements. We assign elements to different linked lists according to their own characteristics, and we find the correct linked list based on these characteristics, and then find the element from the List. the method of calculating the subscript of an array of elements based on the element characteristics is the hashing method.

    • Zipper method of application Scope: Quick find, Delete the basic data structure, usually requires the total amount of data can be put into memory.

    • key points:
      Hash function selection, for strings, integers, permutations, specific hash method;
      Collision handling, An open hashing, also known as the Zipper method, Another is closed hashing, also known as the address law, opened Addressing.

3, Hashcode Brief Introduction
In Java, the hashcode method defined by the object class returns different integers for different objects. (this is done by converting the Object's internal address to an integer, but the JAVATM programming language does not require this implementation technique).

 The general agreement of Hashcode Is:

  • During Java application execution, when the Hashcode method is called multiple times on the same object, the same integer must be returned consistently, provided that the information used to compare the object to equals is not modified. The integer does not need to be consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals (object) method, calling the Hashcode method on each object in both objects must produce the same integer result.

  • If two objects are not equal according to the equals (java.lang.Object) method, calling the Hashcode method on either of these objects does not require that a different integer result be generated. however, programmers should be aware that generating different integer results for unequal objects can improve the performance of the hash Table.
     
    To further understand the role of hashcode, we must first understand the containers in java, because hashcode is only useful in data structures that require hashing algorithms, such as HashSet, HashMap, and Hashtable.

    There are three types of collections in Java (Collection), One is list, one is queue, and the other is Set. Elements within the first two sets are ordered, elements can be duplicated, elements in the last set are unordered, but the elements are not repeatable.

    well, here is a more serious problem: to ensure that elements are not duplicated, can two elements should be repeated based on what to judge? This is the object.equals method. however, if each additional element is checked once, the number of elements that are added to the collection is much more numerous when the element is Many. That is, if there are now 1000 elements in the collection, then the 1001th element joins the collection, it calls the Equals method 1000 Times. This obviously will significantly reduce efficiency. thus, Java uses the principle of a hash table . In this way, we use the hash algorithm to calculate a value for each element that is to be stored in the collection, and then compute the position of the element in the array based on that Value. so, when a collection is to add a new element, it can be divided into two steps:
         

  • The Hashcode method of the element is called first, and then the resulting value is used to calculate the position of the element in the Array. If there is no element in this position, store it directly in this position;

  • If there is already an element in this position, then the Equals method that calls it is compared with the new element: the same is not saved, otherwise it exists in the linked list of this location (Java HashSet, HashMap and Hashtable implementations always put elements into the table header of the list).

4. Equals and Hashcode

 Premise: When it comes to hashcode, we have to say the equals method, both of which are methods in the object class. Because the object class is the base class for all classes, you can override both methods in all Classes.

    • principle 1: If x.equals (y) returns "true", then the hashcode () of x and Y must be equal;
    • principle 2: If x.equals (y) returns "false", then the hashcode () of x and y may be equal or unequal;
    • principle 3: If the hashcode () of x and Y are unequal, then x.equals (y) must return "true";
    • principle 4: in general, The Equals method is called to the user, and the Hashcode method is not called by the general user;
    • principle 5: when an object type is an element of a collection object, the object should have its own equals () and Hashcode () design, and adhere to several of the previous Principles. ;

5. Realization Illustration

Hashcode () is defined in the object class as Follows:

publicnativeinthashCode();

The description is a local method, and its implementation is dependent on the local machine.

This is how the String class overrides it:

 public Final  class Stringimplements Java. io. Serializable, comparable<String;, charsequence{        /** The value is used for character Storage. * *    Private Final Charvalue[];//member Variable 1    /** The offset is the first index of the storage, that is Used. * /    Private Final intOffset//member Variable 2    /** The count is the number of characters in the String. * /    Private Final intCount//member Variable 3   /** Cache The hash code for the string * /    Private intHash//Default to 0//non-member variable     public int hashcode() {intH = hash;intLen = count;//used to member variable 3    if(h = =0&& len >0) {intOff = offset;//used to member variable 2        Charval[] = value;//used to member variable 1             for(inti =0; I < len; I++) {h = to*h + val[off++];//recursive Formula} hash = h; }returnH }}

Explanation of the program: h = s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] it can be seen that the Object's hash address is not necessarily the actual memory address.

V. Summary
    • Hashcode is used by the system to quickly retrieve objects
    • The Equals method is intended to determine whether the referenced object is consistent
    • When overriding the Equals method and the Hashcode method, the member variables used in the Equals method must also be used in the hashcode method, except that the former as a comparison, the latter as the information item that generates the digest, essentially uses the same data, thus guaranteeing the consistency of both.

Reference:

on equals and = = in Java
Thoroughly parse hash table algorithm from beginning to end
Summary of usage of Hashcode method and Equals method in Java
Small examples of hashcode methods in Java
How to use JAVA hashcode
An in-depth analysis of Java equals method and Hashcode method
The hashcode () function in Java to find the hash code value of an object

= = in Java, the difference and connection between equals and Hashcode

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.