equals and hashCode in Java

1. equals method and hashCode method

The equals method and the hashCode method in Java are both methods in the class Object. The equals method is used to detect whether an object is equal to another object, and the default is to compare whether the two objects have the same reference. The hashCode method returns the hash code of the object, the default is the storage address of the object.

Second, the equals method has the characteristics:

    1. Reflexive: for any non-null reference x, x.equals(x) should return true

    2. Symmetry: For any reference x, y, if and only if x.equals(y) returns true, then y.equals(x) should also return true

    3. Transitivity: For any reference x, y, z; if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should also return true

    4. Consistency: If the objects referenced by x and y do not change, then the return value of x.equals(y) will never change

    5. For any non-null reference x, x.equals(null) should return false

3. hashCode returns the hash code of the object. Hash codes are generally used for data structures with hash algorithms, such as hashMap, Hashtable, etc.

    When rewriting hashCode, we should follow certain rules:

    1. If x.equals(y) returns true, then the hashCode values ​​of x and y must be the same

    2. If the property used to calculate the equals method has not changed, then the hashCode always returns the same value

    3. If the equals of two objects returns false, then we do not necessarily require that their hashCodes must be unequal, but the hashCode values ​​are the same, but the equals method is different, which will increase hash conflicts.

Fourth, the role of the hashCode method

    When we add data to the hashMap, if we use the equals method every time to determine whether the keys are the same, the efficiency is too low. So in order to reduce the number of comparisons in the equals method. The role of the hashCode method is used. When putting a key-value pair into a hashMap, first determine the hashCode value, and if the hashCode value is not in the map, put it directly. If they are the same, connect the key-value pair to the original element's linked list.

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325688986&siteId=291194637