Problem Guidance: In the process of learning HashMap, you will encounter the question that to ensure the uniqueness of the key, you need to override the hashCode method, and the equals method.Why do we need to cover the hashCode method and the equals method in order to ensure the uniqueness of the key?
The analysis process is as follows:
HashMapProcess:
1.Each object generates a shaping value (hash code) through the hashCode () method.
2.Handling hash codes:
In the case of HashMap inserting objects and querying objects, the following processes are performed:
1.HashMapIt checks to see if the hash code for the insert object and query object already exists, and if it does not exist, it is added to the HashMap.
2.If the hash code exists, the equals () method is called to process the object to be inserted and the query object, to determine whether the insertion object and the query object have the same key in HashMap, and to replace the old with the new value if the same key exists in HashMap.Value, and return to the old Value
Why do we need to rewrite the eqauls () method?
If two objects are the same (that is, equals returns true when comparing two objects), then their hashCode must be the same as two objects with the same hashCode, and they are not necessarily the same (that is, equals returns false equal when comparing two objects)The s function is a function that all classes inherit from the Object class. When we store our own defined classes in HashMap, the default equals function may not behave as expected.So you need to rewrite.
The problem caused by not rewriting hashCode () method?
When the two objects are the same (that is, when equals compares two objects back to true), their hashCode must be the same.
hashCodeThe same two objects, they are not necessarily the same (that is, when equals compares two objects, it returns false).
If you override equals and keep the hashCode implementation unchanged, the object’s corresponding hashCode is different, it is likely to lead to the following situation: two equal objects A, B, hashCode are different, when saved to HashMa with A as the keyIn p, when B is used as the key to find the value of A, there is a situation that cannot be found.Therefore, we need to rewrite the HashCode () method to ensure that the equal object has a unique hashCode code.
(The author’s knowledge is limited, if there is something wrong, please criticize, correct or contact me.