Java equals() and hashCode() Must Be Overridden Together

𝗪𝗵𝘆 𝗲𝗾𝘂𝗮𝗹𝘀() 𝗮𝗻𝗱 𝗵𝗮𝘀𝗵𝗖𝗼𝗱𝗲() 𝗠𝘂𝘀𝘁 𝗕𝗲 𝗢𝘃𝗲𝗿𝗿𝗶𝗱𝗱𝗲𝗻 𝗧𝗼𝗴𝗲𝘁𝗵𝗲𝗿 𝗶𝗻 𝗝𝗮𝘃𝗮 Many Java developers override equals(). But forget hashCode() And that can break your application in strange ways. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 Imagine you create a class: 𝘤𝘭𝘢𝘴𝘴 𝘜𝘴𝘦𝘳 {   𝘚𝘵𝘳𝘪𝘯𝘨 𝘦𝘮𝘢𝘪𝘭;   @𝘖𝘷𝘦𝘳𝘳𝘪𝘥𝘦   𝘱𝘶𝘣𝘭𝘪𝘤 𝘣𝘰𝘰𝘭𝘦𝘢𝘯 𝘦𝘲𝘶𝘢𝘭𝘴(𝘖𝘣𝘫𝘦𝘤𝘵 𝘰𝘣𝘫) {     // 𝘭𝘰𝘨𝘪𝘤 𝘩𝘦𝘳𝘦   } } Everything seems fine. But when you use this object in a HashMap or HashSet, problems start appearing. Why? Java collections like HashMap use two steps:  • 𝗵𝗮𝘀𝗵𝗖𝗼𝗱𝗲() → decide the bucket  • 𝗲𝗾𝘂𝗮𝗹𝘀() → compare objects inside the bucket If you override only equals() and not hashCode(): Two objects may be equal but end up in different buckets. Result? Your map may behave incorrectly. Correct Rule  • If you override equals(),  • you must override hashCode(). Java’s contract requires both to be consistent. Many strange bugs in collections come from breaking this rule. Small details like this separate average Java developers from strong ones. Have you ever faced a bug because of equals() and hashCode()? #Java #Collections #Programming #SoftwareEngineering #JavaDeveloper #BackendDevelopment #CleanCode

Recently got to know about this through my Team lead, and I was very shocked since I was unaware about this and thankfully I have not missed this in the production code 😂😅

To view or add a comment, sign in

Explore content categories