Interviewer's Favorite Pitfall: Why must I rewrite hashCode when rewriting equals?
AD |
#Autumn Life Clock In Season#Hello, I'm Xiaomi. Welcome to my WeChat official account! Today, we will discuss a frequently asked question in Java development: "Why is rewritingEqualsMethod also needs to be rewrittenHashCodeMethod This question may appear frequently in your interviews, but it is not just an interview question, it also involves very important concepts in Java, Namely object equality and hash codes
#Autumn Life Clock In Season#
Hello, I'm Xiaomi. Welcome to my WeChat official account! Today, we will discuss a frequently asked question in Java development: "Why is rewritingEqualsMethod also needs to be rewrittenHashCodeMethod This question may appear frequently in your interviews, but it is not just an interview question, it also involves very important concepts in Java, Namely object equality and hash codes. Let's delve deeper into this issue and understand why it is so important.
equalandHashCode
In Java, each object has a defaultEqualsMethod, which compares whether the references of objects are equal, that is, comparing whether two objects are the same instance. However, in actual development, we usually need to compare the contents of objects for equality, rather than just comparing their references. That's why we need to rewriteEqualsThe reason for the method.
HashCode..Java...
Equals
By default, in Java, theEqualsThe method compares references to objects. If we don't rewriteEqualsMethod, then for two different objects, even if their contents are the same, callEqualsThe method will also returnFalseBecause their references are different.
Consider the following example:
In this example, althoughPerson1andPerson2The content of is the same, but they are different objects, soEqualsMethod returnFalse. This is obviously not the behavior we want.
To solve this problem, we need to rewriteEqualsMethod to compare the content of an object instead of a reference. Usually, we override in custom classesEqualsMethod to implement our own equality logic and compare whether the properties of an object are equal.
HashCode
Okay, now we know why we need to rewrite itEqualsMethod, but why does it still need to be rewrittenHashCodeWhat about the method? This is because when using hash data structures, such as hash tables, we want equal objects to have equal hash codes.
In Java, hash tables use hash codes to determine the location of stored objects. If two equal objects have different hash codes, they will be stored in different positions in the hash table, resulting in incorrect lookup of these objects.
Consider the following example:
In this example, althoughPerson3andPerson4The content of is the same, but due to their different hash codes,set.contains(Person4)returnFalse. This is because the hash table cannot locate correctlyPerson4.
To solve this problem, we need to ensure that the rewriteEqualsThe object of the method must also be overriddenHashCode ..
HashCode
So, how to rewrite correctlyHashCodeWhat about the method? Java forHashCode .
Here are some rewritesHashCodeRules for methods:
- If two objects pass throughEquals .
- HashCode .
- HashCode ..
- .
.
EqualsandHashCode
Let's take a look at an example of how to rewriteEqualsandHashCodeMethod:
In this example, we have rewritten theEqualsMethod, comparedNameandAgeWhether the attributes are equal and then overriddenHashCodeMethod, usingObjects. hash .
END
To ensure the equality of objects and the correctness of the hash table, we need to rewriteEqualsMethod is also overriddenHashCode ..
When you encounter this issue in an interview, don't forget to emphasize itEqualsandHashCodeConsistency and performance of methods, as well as adherence to rewritingHashCode ..
I hope this article can help you better understand why rewriting is necessaryEqualsMethod also needs to be rewrittenHashCode ..
Knowing what it is and why it is
Disclaimer: The content of this article is sourced from the internet. The copyright of the text, images, and other materials belongs to the original author. The platform reprints the materials for the purpose of conveying more information. The content of the article is for reference and learning only, and should not be used for commercial purposes. If it infringes on your legitimate rights and interests, please contact us promptly and we will handle it as soon as possible! We respect copyright and are committed to protecting it. Thank you for sharing.(Email:[email protected])
Mobile advertising space rental |
Tag: Interviewer Favorite Pitfall Why must rewrite hashCode when rewriting
It was stored in the Yangtze River and dried out! After Samsung's flash memory price reduction, it announced a 50% reduction in production
NextHas Li Ziqi, the former top performer, returned? Can it still lift the top flow storm?
Guess you like
-
The 2025 Chinese New Year (Spring Festival) film box office has exploded, exceeding 3 billion RMB and setting a new record for presales!Detail
2025-01-29 11:55:06 1
-
Seres and Beihang University Join Hands to Build an Innovative Ecosystem, Deepening Industry-Academia-Research Collaboration and Promoting Technological TransformationDetail
2025-01-28 14:46:18 1
-
Douyin 2024 Platform Governance Report: Safeguarding Security, Building a Better CommunityDetail
2025-01-28 14:25:55 1
-
Chinese Scientists Develop a Lightweight Bionic Dexterous Hand with 19 Degrees of Freedom, Promising to Revolutionize Prosthetic and Robotics TechnologyDetail
2025-01-28 14:16:39 1
-
DeepSeek: A Chinese AI Startup's Meteoric Rise Shakes Up Global Tech and Sends US Stocks PlungingDetail
2025-01-28 14:13:23 1
-
WeChat's New Year's Red Envelope Feature Gets a Voice Message Upgrade for Warmer Wishes!Detail
2025-01-26 11:37:36 1
-
360 Digital Security Group and Zhibangyang Education Technology Join Forces to Build a New Ecosystem for Cybersecurity and AI Talent CultivationDetail
2025-01-24 15:09:51 1
-
Visionox Achieves Mass Production of AMOLED with Solid-State Laser Annealing (SLA) Technology, Ushering in a New Era for the Display IndustryDetail
2025-01-24 14:34:23 1
-
Seres at the Davos Forum: The Path to Globalizing New Energy Vehicles Through Cooperation in the Intelligent EraDetail
2025-01-23 13:28:12 1
-
Amazon to Close All French-Speaking Quebec Warehouses, Laying Off Nearly 2,000 EmployeesDetail
2025-01-23 10:51:23 1
-
The official launch of the 2025 Electric Bicycle Trade-in Policy: Upgraded Subsidy Standards, Procedures, and PromotionDetail
2025-01-23 10:48:52 1
-
Xbox Series X|S Officially Supports External Hard Drives Larger Than 16TB: Saying Goodbye to Storage WorriesDetail
2025-01-23 10:39:19 1
-
Leaders from the Beijing Chaoyang District CPPCC Visited Quantum Leap Group, Affirming its Contributions and Future Prospects in the Silver Hair EconomyDetail
2025-01-22 17:06:56 1
-
China's Car Imports Remain Sluggish in 2024: 12% Decline, Sharp Drop in New Energy VehiclesDetail
2025-01-22 11:37:25 1
-
China Railway Group Limited (CRGL) officially debunks "speed-up" ticket booking software: Not a shortcut, but a pathway to riskDetail
2025-01-22 11:36:09 1
-
Dago Bio Completes Over $20 Million A+ Round Funding to Accelerate Novel Molecular Glue Drug DevelopmentDetail
2025-01-22 11:34:05 11
-
Rapid Degradation of Global Lake Submerged Vegetation: Satellite Observations Reveal a Critical Period of Ecosystem ShiftDetail
2025-01-22 11:29:03 1
-
Star Ace Capital Group and Abu Dhabi Investment Office Partner to Build a Global Esports Industry BenchmarkDetail
2025-01-22 11:27:50 1
-
Hisense Television Leads the 100-Inch Large-Screen Market in 2024, Achieving an Unparalleled Industry LegacyDetail
2025-01-22 11:12:49 1
-
WeChat Launches "Gifts" Feature: Streamlining Gift-Giving and Powering Social Commerce GrowthDetail
2025-01-21 16:05:45 1