eqauls method and hashCode method

1. The eqauls method and hashCode method in Java

(1) If two objects are the same (equals method returns true), then their hashCode values ​​must be the same

(2) If the hashCode of two objects is the same, they are not necessarily the same (not necessarily the same object)

If you violate the above principles, you will find that when using containers, the same objects can appear in the same Set collection (Set cannot store the same elements), and the efficiency of adding new elements will be greatly reduced (for systems using hash storage , If the frequent collision of hash codes will cause a sharp drop in access performance)

 

2. Features of the equals method

(1) Reflexivity

x.equals(x):true

(2) Symmetry

When x.equals (y) returns true, y.equals (x) must also return true

(3) Transmissibility

When both x.equals (y) and y.equals (z) return true, x.equals (z) must also return true

(4) Consistency

When the object information referenced by x and y has not been modified, multiple calls to x.equals (y) should get the same return value, and for any non-null reference x, x.equals (null) must return false

 

3. Know-how to achieve high-quality equals

(1) Use the == operator to check whether "the parameter is a reference to this object"

(2) Use the instanceof operator to check whether "the parameter is of the correct type"

(3) For the key attributes in the class, check whether the attributes of the parameters passed into the object match it

(4) After writing the equals method, ask yourself if it satisfies symmetry, transitivity, consistency

(5) Always rewrite hashCode when rewriting equals

(6) Do not replace the Object object in the equals method parameter with other types, and do not forget @Override annotation when rewriting

 public  boolean equals (Object obj) {
         // Determine the current object and the passed object 
        if ( this == obj) {
             return  true ; 
        } 
        // Determine whether the object passed in is of the Person type 
        if (! (obj instanceof Person)) {
             return  false ; 
        } 
        // Transform obj down to Perosn reference, you can access the unique content of Person, otherwise you can only access the common content 
        Person p = (Person) obj;
         return  this .age == p.age && this .name == p.name; 
    }

 

Guess you like

Origin www.cnblogs.com/zhai1997/p/12722440.html