Composit PK hashcode与equals

equals:

  public boolean equals(Object obj)

  The default implementation in the Object class is : return this == obj . That is to say, it will only return true if this and obj refer to the same object.

  And we often need to use equals to judge whether two objects are equivalent, rather than verifying their uniqueness. In this way, when we implement our own class, we must override equals.

  By convention, equals must satisfy the following rules:

 Reflexivity: x.equals(x) must be true

  For null: x.equals(null) must be false

  Symmetry: x.equals(y) and y.equals(x) have the same result

  Transitivity: a and b equals, b and c equals, then a and c must also be equals.

  Consistency: During a runtime, changes in the state of the two objects will not affect the decision result of equals, then, during this runtime, no matter how many times equals is called, the same result is returned.

 

hashcode:

  public int hashCode()

  This method returns the hash code of the object, the return value is the hash code of type int.
  The hash code of the object is to better support the Java collection classes based on the hash mechanism, such as Hashtable, HashMap, HashSet, etc.

  Regarding the hashCode method, the consistent convention is:

  Objects that override the euqls method must also override the hashCode() method.

  If two objects return true after being called by equals, then the hashCode method of the two objects must also return the same int hash code

  If 2 objects return false via equals, their hashCode returns are allowed to be the same.

  Consistent conventions for hashCode methods require:

  First: During a runtime period, as long as the object's (field) changes do not affect the decision result of the equals method, then, during this period, no matter how many times hashCode is called, the same hash code must be returned.

  Second: The hashCode of the 2 objects that return true through the equals call must be the same.

  Third: The hash codes of the two objects that return false through equalsl do not need to be different, that is, the return value of their hashCode method allows the same situation.
  To sum up in one sentence: equivalent (calling equals returns true) objects must produce the same hash code. Non-equivalent objects do not require the generated hash codes to be different.

Guess you like

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