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
-
Unitree Robotics Founder Wang Xingxing Releases Video Statement: Warning Against Online Misinformation, Protecting Shareholder InterestsDetail
2025-03-02 12:40:18 1
-
The Age of Smart Homes Arrives: Habitat L32 Ushers in an Upgrade to Living ExperienceDetail
2025-02-28 21:16:59 1
-
Alibaba's DAMO Academy Announces Imminent Delivery of XuanTie C930 Processor, Achieving 15/GHz in SPECint2006 BenchmarkDetail
2025-02-28 11:06:08 1
-
China's OTA Platforms: A High-Efficiency Miracle Under Low Commission RatesDetail
2025-02-28 10:38:34 21
-
China Leads in Setting International Standard for Elderly Care Robots, Ushering in a New Era for the Global Silver EconomyDetail
2025-02-28 10:37:23 1
-
Xiaomi SU7 Ultra: The World's Strongest Four-Door Production Car, 10,000 Pre-orders in Two Hours, Price Drop Ignites the Market!Detail
2025-02-28 10:29:25 1
-
Kingdee Qatar Company Established: Empowering Middle Eastern Enterprises' Digital Transformation with Digital Technology, Driving the "National Vision 2030"Detail
2025-02-28 09:56:02 1
- Detail
-
DeepSeek API Price Adjustment: Off-Peak Discounts Reduce Costs, Up to 75% OffDetail
2025-02-27 10:47:53 21
-
Lenovo's Ask Tian AI Computing Platform Receives Major Upgrade, Enabling Single-Machine Deployment of 671B-Parameter DeepSeek-R1 ModelDetail
2025-02-26 15:22:05 1
-
Largest Mesozoic Scorpion Fossil Discovered in China: Jeholialongchengi Fills Fossil GapDetail
2025-02-26 10:35:56 1
-
Haier Smart Home Leads the Globalization of Appliance Services: Unified Standards, Setting a New Benchmark for Digital ServicesDetail
2025-02-25 17:39:01 1
-
Douyin Livestreaming Shops: A New Engine Driving the Digital Transformation of the Real EconomyDetail
2025-02-25 17:38:14 21
-
Zhou Hongyi, founder of 360 Group, and Nano AI Search's New Energy Vehicle Giveaway Event Concludes Successfully, Marking a Step Forward in AI PopularizationDetail
2025-02-24 18:36:23 31
-
Leaked CAD Renderings Reveal iPhone 17 Series: Two-Tone Back and Novel Camera Designs Spark InterestDetail
2025-02-24 17:27:08 1
-
Yadea Unveils the Modern Series: High-Style Design Meets Tenfold Safety, Ushering in a New Era of Women's CommuteDetail
2025-02-24 14:34:28 1
-
IBM's mandatory return-to-office policy sparks controversy: disguised layoffs, unfair to employees?Detail
2025-02-24 14:15:41 1
-
Apple Halts iCloud Advanced Data Protection in UK: A Stand Against Government 'Backdoor' DemandsDetail
2025-02-24 14:10:40 31
-
S&P Global Sustainability Yearbook 2024: Baidu's Inclusion Highlights the Crucial Role of AI GovernanceDetail
2025-02-19 21:08:50 1
-
Ronshen Refrigerators Lead 2024 Offline Market: Full-Scenario Embedded Refrigerators Drive Consumption UpgradeDetail
2025-02-19 19:12:01 11