Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use hashcode and equals in map

Shulou Source: shulou.com Published: 2022-06-02 09:11:07 09月20日 Update

I believe many inexperienced people don't know what to do about how to use hashcode and equals in map. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

HashMap: linked list + array implementation.

Storage of HashMap: first calculate the location from the hascode through key, and then store it in the linked list.

HashMap finds key: hashMap first locates the array according to the hashcode of the key value, and then matches the same key value according to key's equals method to get the corresponding object.

In other words, the search for a Key is determined by the hashcode and equals methods. If you only implement equals, but not hashcode. Then there must be a problem.

Partial source code:

If (first.hash = = hash & & / / always check first node

((k = first.key) = = key | | (key! = null & & key.equals (k)

Return first

Equals and hascode are two methods of the Java object. The default implementation is equals, which compares the memory addresses of two objects. Hashcode, the hash value calculated from the memory address of the object. If two objects are equal, the hashcode must be equal.

When a certain type of equals is rewritten, the memory addresses of the two object instances are not necessarily the same, and the hashcode is not necessarily the same. According to hashcode's rule, the hashcode of two objects equal must be equal, so a contradiction arises, so rewriting equals must rewrite hashcode.

After reading the above, have you mastered how to use hashcode and equals in map? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Objects two methods same memory address problem location content array more contradiction helplessness for this reason example for this necessity location skill Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker NVidia Shulou Technology Huawei Shulou Tech Info