hashcode() and equals() methods

equals() method

   The equals method in the Object class is the same as "==", there is no difference, that is, the comparison of two objects is to compare the memory addresses stored in their stack memory. And some classes such as String class, Integer class, etc. rewrite the equals method, which makes equals and "== different", they compare whether the values ​​are equal. Therefore, when you create a class yourself, it automatically inherits the equals method of Object. To implement different equal comparisons, you must override the equals method.

  When we new an object, a copy of its own memory will be loaded in memory, not shared! For statically modified variables and methods, they are stored in the method area, loaded only once, and no more memory is copied. Therefore, when we judge whether the two objects are logically equal, that is, whether the contents of the objects are equal, we cannot directly use the equals() method inherited from the Object class. We must override the equals() method and change the default implementation of this method.

  Rewrite the equals method: first determine whether the comparison object is null—> determine whether the comparison object is an instance of the class to be compared—> compare whether the two member variables are completely equal.

hashcode() method:

  When Set receives an element, the hashCode is calculated according to the memory address of the object to see which range it belongs to, and then the equals method is called in this range. It should be noted here that when the hashCode values ​​of the two objects are the same, Hashset will save the objects in the same location, but their equals return false, so in fact, this location uses a chain structure to save multiple objects.

  But one faces a problem: if two objects equals are equal, but not in the same range, because the value of hashCode is calculated from the memory address before rewriting, there is no chance to compare, and they will be considered as different objects. So Java stipulates the equals method and the hashCode method as follows: 
  1. If two objects are the same, then their hashCode values ​​must be the same. It also tells us to rewrite the equals method, we must rewrite the hashCode method, that is to say, the hashCode value must be hooked to the member variable in the class, the object is the same -> the member variable is the same -> the hashCode value must be the same. 
  2. If the hashCode of two objects is the same, they are not necessarily the same. The same object here refers to the comparison using the equals method.

  Note: If we involve the attribute value of the object in the hashCode operation, we cannot modify its attribute value when deleting it, otherwise serious problems will occur.

For details, please refer to: https://blog.csdn.net/qq_21688757/article/details/53067814

Guess you like

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