{"id":7680,"date":"2023-03-30T13:12:46","date_gmt":"2023-03-30T07:42:46","guid":{"rendered":"https:\/\/innovationm.co\/?p=7680"},"modified":"2023-03-30T13:12:46","modified_gmt":"2023-03-30T07:42:46","slug":"role-of-equal-and-hashcode-methods","status":"publish","type":"post","link":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/","title":{"rendered":"Role of equal() and hashCode Methods()"},"content":{"rendered":"<p>In Java, HashMap is a widely used data structure that stores elements in key-value<br \/>\npairs. It provides constant-time performance for basic operations like adding, removing,<br \/>\nand accessing elements. The implementation of HashMap relies heavily on the equals<br \/>\nand hashCode methods, which are used to ensure the uniqueness of keys and the<br \/>\nefficiency of lookup operations. In this article, we&#8217;ll dive deeper into how these methods<br \/>\nare used in HashMap and what effect overriding them can have.<\/p>\n<p><strong>The equals() Method in HashMap:<\/strong><\/p>\n<p>The equals method is used to compare the equality of two objects. In the context of<br \/>\nHashMap is used to compare the keys of the HashMap. When a key is added to the<br \/>\nHashMap, the key&#8217;s equals method is called to check if there is an existing key with the<br \/>\nsame value. If there is, the new value replaces the old one. If not, the key-value pair is<br \/>\nadded to the HashMap.<br \/>\nThe default implementation of the equals method in Java compares the memory<br \/>\naddresses of the two objects. However, in most cases, we want to compare the content<br \/>\nof the objects instead. Therefore, it is often necessary to override the equals method in<br \/>\nthe critical class to ensure that it compares the contents of the objects.<br \/>\nFor example, we have a Student class with name and id attributes. We want to<br \/>\nuse the id as the key in a HashMap, so we need to override the equals method to<br \/>\ncompare the ids instead of the memory addresses.<\/p>\n<pre>\r\npublic class Student {\r\nprivate int id;\r\nprivate String name;\r\npublic Student(int id, String name) {\r\nthis.id = id;\r\nthis.name = name;\r\n}\r\npublic int getId() {\r\nreturn id;\r\n}\r\npublic String getName() {\r\n\r\nreturn name;\r\n}<\/pre>\n<p>@Override<\/p>\n<pre>\r\npublic boolean equals(Object o) {\r\nif (this == o) return true;\r\nif (o == null || getClass() != o.getClass()) return false;\r\nStudent student = (Student) o;\r\nreturn id == student.id;\r\n}\r\n}<\/pre>\n<p><strong>The hashCode() Method in HashMap:<\/strong><\/p>\n<p>The hashCode method returns a hash value that represents the object. In the context of<br \/>\nHashMap is used to determine the index of the bucket where the key-value pair is<br \/>\nstored.<\/p>\n<p>The default implementation of the hashCode method in Java returns the<br \/>\nmemory address of the object as an integer. However, this implementation is not<br \/>\nsuitable for most use cases, as it can result in poor performance and collisions.<br \/>\nTo improve the performance of HashMap, we need to override the hashCode method in<br \/>\nthe key class to produce a more evenly distributed hash value.<\/p>\n<p>The general contract of<br \/>\nthe hashCode method is that if two objects are equal according to the equals method,<br \/>\nthey must have the same hash code. Therefore, it is important to ensure that the<br \/>\nimplementation of the hashCode method is consistent with the implementation of the<br \/>\nequals method.<\/p>\n<p>For example, in our Student class, we can override the hashCode method to return the<br \/>\nhash code of the id attribute:<\/p>\n<p>@Override<\/p>\n<pre>\r\npublic int hashCode() {\r\nreturn Objects.hash(id);\r\n}<\/pre>\n<p><strong>Effect of Overriding equals and hashCode Methods in HashMap:<\/strong><\/p>\n<p>When we override the equals and hashCode methods in the key class, we need to<br \/>\nensure that the implementation is consistent with the semantics of the class. If two<br \/>\nobjects are equal according to the equals method, they must have the same hash code.<br \/>\nIf two things have the same hash code, they may or may not be equal according to the<br \/>\nequals method.<\/p>\n<p>If the implementation of the equals and hashCode methods is incorrect, it can result in<br \/>\nunexpected behavior, such as incorrect lookup results or the loss of key-value pairs.<br \/>\nTherefore, it is important to test the implementation of these methods thoroughly and<br \/>\nensure that they adhere to the contracts.<br \/>\nIn conclusion, the equals and hashCode methods are essential components of the<br \/>\nHashMap implementation<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Java, HashMap is a widely used data structure that stores elements in key-value pairs. It provides constant-time performance for basic operations like adding, removing, and accessing elements. The implementation of HashMap relies heavily on the equals and hashCode methods, which are used to ensure the uniqueness of keys and the efficiency of lookup operations. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":7681,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[360],"tags":[722,845,846,847,346],"class_list":["post-7680","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","tag-blog","tag-equal","tag-hashcode","tag-java-methods","tag-javascript"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Role of equal() and hashCode Methods() - InnovationM - Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Role of equal() and hashCode Methods() - InnovationM - Blog\" \/>\n<meta property=\"og:description\" content=\"In Java, HashMap is a widely used data structure that stores elements in key-value pairs. It provides constant-time performance for basic operations like adding, removing, and accessing elements. The implementation of HashMap relies heavily on the equals and hashCode methods, which are used to ensure the uniqueness of keys and the efficiency of lookup operations. [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/\" \/>\n<meta property=\"og:site_name\" content=\"InnovationM - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2023-03-30T07:42:46+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2023\/03\/Role-of-equal-and-hashCode-Methods.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1689\" \/>\n\t<meta property=\"og:image:height\" content=\"950\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"InnovationM Admin\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"InnovationM Admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/\"},\"author\":{\"name\":\"InnovationM Admin\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#\\\/schema\\\/person\\\/a831bf4602d69d1fa452e3de0c8862ed\"},\"headline\":\"Role of equal() and hashCode Methods()\",\"datePublished\":\"2023-03-30T07:42:46+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/\"},\"wordCount\":562,\"commentCount\":0,\"image\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/03\\\/Role-of-equal-and-hashCode-Methods.png\",\"keywords\":[\"blog\",\"equal\",\"hashcode\",\"java methods\",\"JavaScript\"],\"articleSection\":[\"JavaScript\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/\",\"url\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/\",\"name\":\"Role of equal() and hashCode Methods() - InnovationM - Blog\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/03\\\/Role-of-equal-and-hashCode-Methods.png\",\"datePublished\":\"2023-03-30T07:42:46+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#\\\/schema\\\/person\\\/a831bf4602d69d1fa452e3de0c8862ed\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/03\\\/Role-of-equal-and-hashCode-Methods.png\",\"contentUrl\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/03\\\/Role-of-equal-and-hashCode-Methods.png\",\"width\":1689,\"height\":950},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/role-of-equal-and-hashcode-methods\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Role of equal() and hashCode Methods()\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/\",\"name\":\"InnovationM - Blog\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#\\\/schema\\\/person\\\/a831bf4602d69d1fa452e3de0c8862ed\",\"name\":\"InnovationM Admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g\",\"caption\":\"InnovationM Admin\"},\"sameAs\":[\"http:\\\/\\\/www.innovationm.com\\\/\"],\"url\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/author\\\/innovationmadmin\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Role of equal() and hashCode Methods() - InnovationM - Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/","og_locale":"en_US","og_type":"article","og_title":"Role of equal() and hashCode Methods() - InnovationM - Blog","og_description":"In Java, HashMap is a widely used data structure that stores elements in key-value pairs. It provides constant-time performance for basic operations like adding, removing, and accessing elements. The implementation of HashMap relies heavily on the equals and hashCode methods, which are used to ensure the uniqueness of keys and the efficiency of lookup operations. [&hellip;]","og_url":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/","og_site_name":"InnovationM - Blog","article_published_time":"2023-03-30T07:42:46+00:00","og_image":[{"width":1689,"height":950,"url":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2023\/03\/Role-of-equal-and-hashCode-Methods.png","type":"image\/png"}],"author":"InnovationM Admin","twitter_misc":{"Written by":"InnovationM Admin","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/#article","isPartOf":{"@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/"},"author":{"name":"InnovationM Admin","@id":"https:\/\/www.innovationm.com\/blog\/#\/schema\/person\/a831bf4602d69d1fa452e3de0c8862ed"},"headline":"Role of equal() and hashCode Methods()","datePublished":"2023-03-30T07:42:46+00:00","mainEntityOfPage":{"@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/"},"wordCount":562,"commentCount":0,"image":{"@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/#primaryimage"},"thumbnailUrl":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2023\/03\/Role-of-equal-and-hashCode-Methods.png","keywords":["blog","equal","hashcode","java methods","JavaScript"],"articleSection":["JavaScript"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/","url":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/","name":"Role of equal() and hashCode Methods() - InnovationM - Blog","isPartOf":{"@id":"https:\/\/www.innovationm.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/#primaryimage"},"image":{"@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/#primaryimage"},"thumbnailUrl":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2023\/03\/Role-of-equal-and-hashCode-Methods.png","datePublished":"2023-03-30T07:42:46+00:00","author":{"@id":"https:\/\/www.innovationm.com\/blog\/#\/schema\/person\/a831bf4602d69d1fa452e3de0c8862ed"},"breadcrumb":{"@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/#primaryimage","url":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2023\/03\/Role-of-equal-and-hashCode-Methods.png","contentUrl":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2023\/03\/Role-of-equal-and-hashCode-Methods.png","width":1689,"height":950},{"@type":"BreadcrumbList","@id":"https:\/\/www.innovationm.com\/blog\/role-of-equal-and-hashcode-methods\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.innovationm.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Role of equal() and hashCode Methods()"}]},{"@type":"WebSite","@id":"https:\/\/www.innovationm.com\/blog\/#website","url":"https:\/\/www.innovationm.com\/blog\/","name":"InnovationM - Blog","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.innovationm.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.innovationm.com\/blog\/#\/schema\/person\/a831bf4602d69d1fa452e3de0c8862ed","name":"InnovationM Admin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g","caption":"InnovationM Admin"},"sameAs":["http:\/\/www.innovationm.com\/"],"url":"https:\/\/www.innovationm.com\/blog\/author\/innovationmadmin\/"}]}},"_links":{"self":[{"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/posts\/7680","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/comments?post=7680"}],"version-history":[{"count":0,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/posts\/7680\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/media\/7681"}],"wp:attachment":[{"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/media?parent=7680"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/categories?post=7680"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/tags?post=7680"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}