Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use hashcode and equals in map

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report