Home >Java >javaTutorial >Summary of the usage of equals and hashCode
一equals
##The equals method is Object-level. By default, it compares the memory addresses of two objects. Many classes have overridden this method to compare the actual contents of the objects. , generally compare whether the attribute values of the same attributes of the same type of objects are the same.
The hash table is an array, Each element in the array is a one-way linked list. The nodes in the same one-way linked list have the same attributes. The attribute value is the subscript of the array. This same attribute is called hashCode hash value. .
Before hashCode is generated, the retrieval set needs to be compared one by one, which results in low query efficiency. If elements with the same attribute value in a collection are divided into a group based on a certain attribute, is stored centrally. When querying, the value of the attribute of the query object is first obtained, and the corresponding group is located based on the value, which greatly reduces the problem. It increases the query scope and improves the query efficiency. This is the background of hashCode.
The hashCode of two objects is equal, which only indicates that they are in the same group. It is not guaranteed to be the same. You must also compare the memory addresses of the two objects or pass ## The #equals method compares the specific contents. Only when this item is satisfied can it be determined that the two objects are the same.
It can be seen from the above that in the hash table, the same two objects must have the same hash value.3.hashCode() method
only to ensure that the attribute values of the same attributes are the same, without rewriting the hashCode, the hash values are different and are stored in are treated as two objects with different contents in the hash table, resulting in two elements with the same content appearing in the hash table, occupying unnecessary memory. Therefore, once the equals method is rewritten, it must be rewritten. Write the hashCode method and ensure that the same objects have equal values.
Three applicationsmust override the equals and hashCode methods in the class so that the same objects have equal hash values.
The above is the detailed content of Summary of the usage of equals and hashCode. For more information, please follow other related articles on the PHP Chinese website!