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
-
China Leads in Developing IEC 63206 International Standard, Driving Global Innovation in Industrial Process Control System RecordersDetail
2025-01-18 11:06:14 1
-
The 2024 Micro-Short Series Industry Ecological Insight Report: 647,000 Job Opportunities, Rise of Diversified Business Models, and High-Quality Content as the Future TrendDetail
2025-01-17 17:33:01 1
-
Global PC Market Shows Moderate Recovery in 2024: High AIPC Prices a Bottleneck, Huge Growth Potential in 2025Detail
2025-01-17 11:02:09 1
-
Bosch's Smart Cockpit Platform Surpasses 2 Million Units Shipped, Showcasing Strength in Intelligent Driving TechnologyDetail
2025-01-17 10:55:29 1
-
YY Guangzhou Awarded "2024 Network Information Security Support Unit" for Outstanding ContributionsDetail
2025-01-17 10:43:28 1
-
TikTok CEO Invited to Trump's Inauguration, Biden Administration May Delay BanDetail
2025-01-16 20:06:11 1
-
Douyin Denies Opening International Registration: Overseas IPs Don't Equate to Overseas Registration; Platform Actively Combats Account ImpersonationDetail
2025-01-16 14:26:12 1
-
Lei Jun, Xiaomi's founder, chairman, and CEO, has set a new goal: learning to drive a forklift!Detail
2025-01-15 10:22:30 11
-
ByteDance Scholarship 2024: Fifteen Outstanding Doctoral Students Awarded RMB 100,000 Each to Advance Frontier Technology ExplorationDetail
2025-01-14 15:56:39 1
-
Fliggy Launches "Peace of Mind for the New Year" Service Initiative to Ensure Smooth Travel During the Year of the Snake Spring Festival RushDetail
2025-01-14 15:24:53 1
-
Arm's Massive Fee Hike and Potential In-House Chip Development: A Precursor to a Seismic Shift in the Chip Industry?Detail
2025-01-14 11:02:36 1
-
Adobe Firefly Launches: Generative AI Suite Revolutionizes Image and Video Processing EfficiencyDetail
2025-01-14 10:46:39 1
-
Chinese New Year Elements Sell Like Hotcakes Overseas: Cross-border E-commerce "Spring Festival Economy" Booms, Cainiao Overseas Warehouses Help Merchants Capture Market ShareDetail
2025-01-13 14:17:50 1
-
China Railway's 12306 System Successfully Navigates Spring Festival Travel RushDetail
2025-01-13 12:56:54 1
-
Handan, Hebei Province Successfully Tests First Low-Altitude Drone Delivery Route, Ushering in a New Era of Smart LogisticsDetail
2025-01-13 12:50:13 1
-
Kuaishou Leads in Developing Anti-Fraud Industry Standards, Contributing to a Secure and Reliable Short-Video CommunityDetail
2025-01-13 09:47:32 11
-
Microsoft Offers Top Salaries to Retain AI Talent: AI Software Engineers Earn Over $400,000 AnnuallyDetail
2025-01-12 17:28:34 11
- Detail
-
Chang'e-5 Mission Unveils Secrets: New Discoveries Regarding Lunar Magnetic Field Strength and Deep Dynamics 2 Billion Years AgoDetail
2025-01-10 11:42:44 11
-
SenseTime's "Day Day New" Multimodal Large Model: Native Fusion Enables Diverse ApplicationsDetail
2025-01-10 11:40:40 21