{"id":1943,"date":"2011-04-11T15:42:21","date_gmt":"2011-04-11T10:12:21","guid":{"rendered":"http:\/\/JitendraZaa.com\/blog\/?p=1943"},"modified":"2011-04-11T15:42:21","modified_gmt":"2011-04-11T10:12:21","slug":"what-is-the-need-to-override-hashcode-and-equals-method","status":"publish","type":"post","link":"https:\/\/www.jitendrazaa.com\/blog\/java\/what-is-the-need-to-override-hashcode-and-equals-method\/","title":{"rendered":"What is the need to Override Hashcode() and equals() method"},"content":{"rendered":"<p>Although there are lots of materials are available on internet and API document about the necessity of the overriding the <strong>hashcode() <\/strong>and <strong>equals() <\/strong>method in Java but lots of new developers still not able to understand the necessity of <strong>hashcode() <\/strong>method.<br \/>\nIn this article, I will try to explain step by step the need of overriding <strong>hashcode()<\/strong> method in Java.<\/p>\n<p><strong>Few Thump rules:<\/strong><\/p>\n<ul>\n<li>If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.<\/li>\n<li>It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.<\/li>\n<\/ul>\n<blockquote><p><strong>JVM assigns unique hashcode value to each object when they are created in memory and if developers don&#8217;t override the hashcode method then there is no way the two object returns same hashcode value.<\/strong><\/p><\/blockquote>\n<p>As the question comes in your mind that equals() method is used to compare objects that they are having same value or not but <strong>why should we override the hashcode method ?<\/strong><\/p>\n<p>The answer to the question is for the hash technique based data structures like HashMap and HashTable.<!--more--><\/p>\n<figure id=\"attachment_1946\" aria-describedby=\"caption-attachment-1946\" style=\"width: 444px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/04\/How-Hashcode-works-in-java.jpg?ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-1946 \" title=\"How Hashcode works in java\" src=\"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/04\/How-Hashcode-works-in-java.jpg?resize=444%2C210&#038;ssl=1\" alt=\"How Hashcode works in java\" width=\"444\" height=\"210\" \/><\/a><figcaption id=\"caption-attachment-1946\" class=\"wp-caption-text\">How Hashcode works in java<\/figcaption><\/figure>\n<p>As you can see in above diagram that every object is placed in Hash bucket depending on the hashcode they have. It is not necessary that every different object must have different hashcode. <strong>hashcode is used to narrow the search result. <\/strong>When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method. If two objects are same then HashMap will not add that key instead it will replace the old value by new one.<\/p>\n<p><strong>What will happen if I don&#8217;t override the hashcode method?<\/strong><br \/>\nAns : If the object does not implement hashcode() method and used as key then we will not get the object back as shown in below code.<\/p>\n<hr \/>\n<p><strong>Code without implementation of equals() and hashcode()<\/strong><\/p>\n<pre class=\"brush: java; highlight: [62,63]; title: ; notranslate\" title=\"\">\npackage com.G2.Collections;\n\nimport java.util.HashMap;\n\nclass Movie {\n\tprivate String name, actor;\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getActor() {\n\t\treturn actor;\n\t}\n\n\tpublic void setActor(String actor) {\n\t\tthis.actor = actor;\n\t}\n\n\tpublic int getReleaseYr() {\n\t\treturn releaseYr;\n\t}\n\n\tpublic void setReleaseYr(int releaseYr) {\n\t\tthis.releaseYr = releaseYr;\n\t}\n\n\tprivate int releaseYr;\n}\n\npublic class HashMapDemo {\n\n\tpublic static void main(String&#x5B;] args) {\n\n\t\tMovie m = new Movie();\n\t\tm.setActor(&quot;Akshay&quot;);\n\t\tm.setName(&quot;Thank You&quot;);\n\t\tm.setReleaseYr(2011);\n\n\t\tMovie m1 = new Movie();\n\t\tm1.setActor(&quot;Akshay&quot;);\n\t\tm1.setName(&quot;Khiladi&quot;);\n\t\tm1.setReleaseYr(1993);\n\n\t\tMovie m2 = new Movie();\n\t\tm2.setActor(&quot;Akshay&quot;);\n\t\tm2.setName(&quot;Taskvir&quot;);\n\t\tm2.setReleaseYr(2010);\n\n\t\tMovie m3 = new Movie();\n\t\tm3.setActor(&quot;Akshay&quot;);\n\t\tm3.setName(&quot;Taskvir&quot;);\n\t\tm3.setReleaseYr(2010);\n\n\t\tHashMap&lt;Movie, String&gt; map = new HashMap&lt;Movie, String&gt;();\n\t\tmap.put(m, &quot;ThankYou&quot;);\n\t\tmap.put(m1, &quot;Khiladi&quot;);\n\t\tmap.put(m2, &quot;Tasvir&quot;);\n\t\tmap.put(m3, &quot;Duplicate Tasvir&quot;);\n\n\t\t\/\/Iterate over HashMap\n\t\tfor (Movie mm : map.keySet()) {\n\t\t\tSystem.out.println(map.get(mm).toString());\n\t\t}\n\n\t\tMovie m4 = new Movie();\n\t\tm4.setActor(&quot;Akshay&quot;);\n\t\tm4.setName(&quot;Taskvir&quot;);\n\t\tm4.setReleaseYr(2010);\n\n\/* We are trying to retrieve m2, by creating object m4 with exact values as of m2, However Hashcode method is not implemented and that why we are not able to get Object m2 *\/\n\t\tif(map.get(m4) == null ){\n\t\t\tSystem.out.println(&quot;----------------&quot;);\n\t\t\tSystem.out.println(&quot;Object not found&quot;);\n\t\t\tSystem.out.println(&quot;----------------&quot;);\n\t\t}else{\n\t\t\tSystem.out.println(map.get(m4).toString());\n\t\t}\n\t}\n}\n\n<\/pre>\n<p><strong>Output:<\/strong><br \/>\nKhiladi<br \/>\nTasvir<br \/>\nThankYou<br \/>\nDuplicate Tasvir<br \/>\n&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\nObject not found<br \/>\n&#8212;&#8212;&#8212;&#8212;&#8212;-<\/p>\n<p>As you can see in above program :<\/p>\n<ol>\n<li>Duplicate objects are added in Hashmap as a key (Because we have not overided the hashcode and equals method)<\/li>\n<li>We are not able to get back object from map (Because hashcode is not implemented)<\/li>\n<\/ol>\n<hr \/>\n<p><strong>Same program with equals and hashcode implementation:<\/strong><\/p>\n<pre class=\"brush: java; highlight: [9,10,11,12,14,15,16,17,73,74]; title: ; notranslate\" title=\"\">\npackage com.G2.Collections;\n\nimport java.util.HashMap;\n\nclass Movie {\n\tprivate String name, actor;\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tMovie m = (Movie) o;\n\t\treturn m.actor.equals(this.actor) &amp;&amp; m.name.equals(this.name) &amp;&amp; m.releaseYr == this.releaseYr;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn actor.hashCode() + name.hashCode() + releaseYr;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getActor() {\n\t\treturn actor;\n\t}\n\n\tpublic void setActor(String actor) {\n\t\tthis.actor = actor;\n\t}\n\n\tpublic int getReleaseYr() {\n\t\treturn releaseYr;\n\t}\n\n\tpublic void setReleaseYr(int releaseYr) {\n\t\tthis.releaseYr = releaseYr;\n\t}\n\n\tprivate int releaseYr;\n}\n\npublic class HashMapDemo {\n\n\tpublic static void main(String&#x5B;] args) {\n\n\t\tMovie m = new Movie();\n\t\tm.setActor(&quot;Akshay&quot;);\n\t\tm.setName(&quot;Thank You&quot;);\n\t\tm.setReleaseYr(2011);\n\n\t\tMovie m1 = new Movie();\n\t\tm1.setActor(&quot;Akshay&quot;);\n\t\tm1.setName(&quot;Khiladi&quot;);\n\t\tm1.setReleaseYr(1993);\n\n\t\tMovie m2 = new Movie();\n\t\tm2.setActor(&quot;Akshay&quot;);\n\t\tm2.setName(&quot;Taskvir&quot;);\n\t\tm2.setReleaseYr(2010);\n\n\t\tMovie m3 = new Movie();\n\t\tm3.setActor(&quot;Akshay&quot;);\n\t\tm3.setName(&quot;Taskvir&quot;);\n\t\tm3.setReleaseYr(2010);\n\n\t\tHashMap&lt;Movie, String&gt; map = new HashMap&lt;Movie, String&gt;();\n\t\tmap.put(m, &quot;ThankYou&quot;);\n\t\tmap.put(m1, &quot;Khiladi&quot;);\n\t\tmap.put(m2, &quot;Tasvir&quot;);\n\t\tmap.put(m3, &quot;Duplicate Tasvir&quot;);\n\n\t\t\/\/ Iterate over HashMap\n\t\tfor (Movie mm : map.keySet()) {\n\t\t\tSystem.out.println(map.get(mm).toString());\n\t\t}\n\n\t\tMovie m4 = new Movie();\n\t\tm4.setActor(&quot;Akshay&quot;);\n\t\tm4.setName(&quot;Taskvir&quot;);\n\t\tm4.setReleaseYr(2010);\n\n\t\tif (map.get(m4) == null) {\n\t\t\tSystem.out.println(&quot;----------------&quot;);\n\t\t\tSystem.out.println(&quot;Object not found&quot;);\n\t\t\tSystem.out.println(&quot;----------------&quot;);\n\t\t} else {\n\t\t\tSystem.out.println(&quot;----------------&quot;);\n\t\t\tSystem.out.println(map.get(m4).toString());\n\t\t\tSystem.out.println(&quot;----------------&quot;);\n\t\t}\n\t}\n}\n\n<\/pre>\n<p><strong>Output:<\/strong><br \/>\nKhiladi<br \/>\nDuplicate Tasvir<br \/>\nThankYou<br \/>\n&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\nDuplicate Tasvir<br \/>\n&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\nAs you can see :<\/p>\n<ul>\n<li>Duplicate Keys are not added instead there values are replaced.<\/li>\n<li>Now the object is retrieved from the Map.<\/li>\n<\/ul>\n<hr \/>\n<p><strong>Ques : How to iterate over keyset of HashMap in JDK 4 and 5?<\/strong><br \/>\nAns : This is the common question asked in interview.<\/p>\n<p><strong>In JAVA 5 : <\/strong>we can use advance for loop as shown in above code, use map.keySet(). This will return the <a title=\"Set Interface API\" href=\"http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/Set.html\" target=\"_blank\">Set <\/a>(As Keys must be unique)<\/p>\n<p><strong>In JAVA 4 :<\/strong> use map.keySet() and get the <a title=\"Iterator API\" href=\"http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/Iterator.html\" target=\"_blank\">Iterator <\/a>object using map.<a title=\"iterator() method API\" href=\"http:\/\/download.oracle.com\/javase\/1.5.0\/docs\/api\/java\/util\/Set.html#iterator%28%29\" target=\"_blank\">iterate()<\/a> . then using while loop , get the value for each key.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Although there are lots of material are available on internet and API document about the necessity of the overriding the hashcode() and equals() method in Java but lots of new developers still not able to understand the necessity of hashcode() method.<br \/>\nIn this article, I will try to explain step by step the need of overriding hashcode() method in Java.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"jz_research_post":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[3],"tags":[329],"class_list":["post-1943","post","type-post","status-publish","format-standard","hentry","category-java","tag-java"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":1655,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/introduction-to-annotation-in-java\/","url_meta":{"origin":1943,"position":0},"title":"Introduction to Annotation in JAVA","author":"Jitendra","date":"March 14, 2011","format":false,"excerpt":"Introduction to Annotation in JAVA","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3050,"url":"https:\/\/www.jitendrazaa.com\/blog\/salesforce\/my-favorite-top-10-features-of-winter-13-release-salesforce\/","url_meta":{"origin":1943,"position":1},"title":"My Favorite Top 10 Features of Winter 13 release &#8211; Salesforce","author":"Jitendra","date":"August 24, 2012","format":false,"excerpt":"Dear Friends, I am very excited to write this article about the cool Winter 13 features which i have added in My List. There are lots of lots of new features added in this release and i have made the list of my top 10 favorite features. Yesterday Salesforce published\u2026","rel":"","context":"In &quot;Salesforce&quot;","block_context":{"text":"Salesforce","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/salesforce\/"},"img":{"alt_text":"Salesforce Winter 13 Release Notes","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2012\/08\/Salesforce-Winter-13-Release-Notes-300x212.jpg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1494,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/servlet\/life-cycle-of-servlet\/","url_meta":{"origin":1943,"position":2},"title":"Life Cycle of Servlet","author":"Jitendra","date":"February 12, 2011","format":false,"excerpt":"Explain Life Cycle of Servlet","rel":"","context":"In &quot;Servlet&quot;","block_context":{"text":"Servlet","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/servlet\/"},"img":{"alt_text":"Servlet Life Cycle","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/02\/Servlet-Life-Cycle.jpg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1937,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/virtual-function-in-java\/","url_meta":{"origin":1943,"position":3},"title":"Virtual Function in JAVA","author":"Jitendra","date":"April 8, 2011","format":false,"excerpt":"Example and explanation of Virtual Function in JAVA","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1479,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/servlet\/example-to-override-the-init-method-of-the-servlet\/","url_meta":{"origin":1943,"position":4},"title":"Example to Override the init() method of the servlet","author":"Jitendra","date":"February 11, 2011","format":false,"excerpt":"Example to Override the init() method of the servlet","rel":"","context":"In &quot;Servlet&quot;","block_context":{"text":"Servlet","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/servlet\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2017,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/java-j2ee-interview-questions-1\/","url_meta":{"origin":1943,"position":5},"title":"Java &#8211; J2EE Interview Questions &#8211; 1","author":"Jitendra","date":"April 15, 2011","format":false,"excerpt":"JAVA - J2EE Interview Questions - 1, JAVA - J2EE Interview Questions - 1,custom tag JSP, Externalization , serialVersionUID, difference between interface and abstract class, iterate HashMap","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1943","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/comments?post=1943"}],"version-history":[{"count":0,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1943\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/media?parent=1943"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/categories?post=1943"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/tags?post=1943"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}