The role of hashcode and equals the difference and contact

Summary:

hashCode and equals that of the same seemingly small role but it has a very different product, you are comparing the value I have a different standard of measurement. I suggest we have agreed to a rule, to better serve the application bar

There are so two conclusions:

1, two objects are equal equals their hashCode certainly equal, it equals is absolutely reliable.

2, two objects are equal hashCode their equals are not necessarily equal, hashCode is not infallible.

What is HashCode (hash code)

Role hashCode () Gets the hash code is, it is an int integer. The role of this hash code is to determine the location of the object in the hash index list. hashCode defined in java.Object, meaning each class has a hashCode function.
public class Demo{
       public static void main (String []args){
              String  str = "aa";
              System.out,println(str.hashCode())
      }
}
             // results
3104

What are the equals

Determining whether two objects are equal, that is, "==", addresses of the two objects are the same; if the object overrides the equals () method, the content of the object are equal comparison. The same definition of equals in java.Object in, Java has any class equals method.

The figure is not a method override equals () of

 

 

 Since then the two objects of different addresses, different resulting hashCode, even as their name, but "==" and "equals ()" is not equal, returns false.

 

      If we want two objects are equal two name system it is considered to be the same, that is, when the method returns true or "==", then you need to override the equals method calls equals (). And in many situations, we determined that the two are not the same name, is not required to determine additional information, such as addresses. How to rewrite it?

Override equals () method must satisfy several conditions

  • Reflexive: for any non-null reference x, x.equals (x) returns true.
  • Symmetry: x and y, x.equals (y) returns true for any reference, y.equals (x) should return to true.
  • Transitive: for any reference to x, y and z, if x.equals (y) returns true, y.equals (z) returns true, then x.equals (z) should return true.
  • Consistency: If the object referenced by x and y are not changed, then the result is called repeatedly x.equals (y) obtained in the same.
  • Nonemptiness: x for any non-null reference, results x.equals (null) be false.

Override the equals method must override the hashCode method returns true because you then have to address value equal to such conditions as to ensure equal equals

 

 

Guess you like

Origin www.cnblogs.com/hjdk05/p/11944508.html