SlideShare a Scribd company logo
Java Equals HashCode Contract
Sujit Kumar
Zenolocity LLC © 2013-2023
The Contract
• 2 equal objects should have the same
hashCode.
• The reverse may or may not be true => 2
objects with the same hashCode may or may
not be equal.
Default implementations in Object
class
• The default implementation of hashCode() in
Object class returns distinct integers for
different objects.
• The default implementation of equals() in
Object class is reference equality, and
therefore two instances are the same if and
only if they are the same instance.
Class with equals() but no hashCode()
public class Banana {
private String color;
public Banana (String color) {
this.color = color;
}
public boolean equals(Object obj) {
if (!(obj instanceof Banana)) return false;
if (obj == this) return true;
return this.color.equals(((Banana) obj).color);
}
}
equals() provided without hashCode()
Banana a1 = new Banana("green");
Banana a2 = new Banana(“yellow”);
//hashMap stores Banana type and its quantity
HashMap<Banana, Integer> m = new HashMap<Banana,
Integer>();
m.put(a1, 10);
m.put(a2, 20);
// Returns null even though the map contains a green Banana
System.out.println(m.get(new Banana("green")));
Add hashCode() method to Class
public int hashCode() {
return 29 * this.color.hashCode();
}
// Returns the green Banana now !
System.out.println(m.get(new Banana("green")));
Hash Collisions
• put method – calculates the hashCode on the key and
places the key-value pair in a bucket for that hashCode
value.
• The next put may result in the same hashCode if the
hashCode method is not good enough to produce a unique
value. This results in a hash collision.
• Hash Collision results in multiple entries (k-v pairs) put in
the same bucket in the form of a list.
• When you retrieve using the get method, calculate the
hashCode, go to the bucket & retrieve from the list in the
bucket by invoking the equals method for each key in the
list.
• Hash Collisions degrade performance.
Techniques to make a hashCode
unique
• Invoke the hashCode on each instance
variable, multiply with a prime number like 29
and keep adding the results.
• Return the final result.

More Related Content

What's hot (20)

PPTX
16 containers
dhrubo kayal
 
PDF
Python tuple
Mohammed Sikander
 
PDF
Hashtable
uo168319
 
PPTX
Regular Expressions in JavaScript and Command Line
Mandi Grant
 
PPTX
Quadratic probing
rajshreemuthiah
 
PDF
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
PPT
Hashing gt1
Gopi Saiteja
 
PDF
Python List Comprehensions
Yos Riady
 
PDF
Using Affordance for Clearer Source Code
davidolesch
 
PDF
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Kuntal Bhowmick
 
PPT
Hashing PPT
Saurabh Kumar
 
PPTX
Hashing data
umair khan
 
PPTX
List in Python
Siddique Ibrahim
 
PPT
18 hashing
deonnash
 
PPT
Data Structure and Algorithms Hashing
ManishPrajapati78
 
PPT
Hashing
amoldkul
 
PDF
Color picker2
ArnabBandopadhyaya
 
PPTX
Statistics - ArgMax Equation
Andrew Ferlitsch
 
PPTX
Hashing
Dinesh Vujuru
 
16 containers
dhrubo kayal
 
Python tuple
Mohammed Sikander
 
Hashtable
uo168319
 
Regular Expressions in JavaScript and Command Line
Mandi Grant
 
Quadratic probing
rajshreemuthiah
 
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Hashing gt1
Gopi Saiteja
 
Python List Comprehensions
Yos Riady
 
Using Affordance for Clearer Source Code
davidolesch
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Kuntal Bhowmick
 
Hashing PPT
Saurabh Kumar
 
Hashing data
umair khan
 
List in Python
Siddique Ibrahim
 
18 hashing
deonnash
 
Data Structure and Algorithms Hashing
ManishPrajapati78
 
Hashing
amoldkul
 
Color picker2
ArnabBandopadhyaya
 
Statistics - ArgMax Equation
Andrew Ferlitsch
 
Hashing
Dinesh Vujuru
 

Similar to Java equals hashCode Contract (12)

ODT
Java%20 new%20faq.doc 0
aravind_aashu
 
PPTX
Java Collections.pptx
AbhishekKudal2
 
DOCX
Core Java Equals and hash code
mhtspvtltd
 
PPT
hashcode hash map hashing hashset hashing
ebtehally95
 
PPTX
Methods common to all objects
Sandeep Chawla
 
PPT
Hashing data structure in genaral ss.ppt
ssusere3b1a2
 
ODP
Object Equality in Scala
Knoldus Inc.
 
PDF
RubyMiniGuide-v1.0_0
tutorialsruby
 
PDF
RubyMiniGuide-v1.0_0
tutorialsruby
 
PPTX
Module 2 Javascript. Advanced concepts of javascript
BKReddy3
 
PDF
16 ruby hashes
Walker Maidana
 
PPT
Java Presentation
mdfkhan625
 
Java%20 new%20faq.doc 0
aravind_aashu
 
Java Collections.pptx
AbhishekKudal2
 
Core Java Equals and hash code
mhtspvtltd
 
hashcode hash map hashing hashset hashing
ebtehally95
 
Methods common to all objects
Sandeep Chawla
 
Hashing data structure in genaral ss.ppt
ssusere3b1a2
 
Object Equality in Scala
Knoldus Inc.
 
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
tutorialsruby
 
Module 2 Javascript. Advanced concepts of javascript
BKReddy3
 
16 ruby hashes
Walker Maidana
 
Java Presentation
mdfkhan625
 
Ad

More from Sujit Kumar (20)

PPTX
Introduction to OOP with java
Sujit Kumar
 
PPTX
SFDC Database Basics
Sujit Kumar
 
PPTX
SFDC Database Security
Sujit Kumar
 
PPTX
SFDC Social Applications
Sujit Kumar
 
PPTX
SFDC Other Platform Features
Sujit Kumar
 
PPTX
SFDC Outbound Integrations
Sujit Kumar
 
PPTX
SFDC Inbound Integrations
Sujit Kumar
 
PPTX
SFDC UI - Advanced Visualforce
Sujit Kumar
 
PPTX
SFDC UI - Introduction to Visualforce
Sujit Kumar
 
PPTX
SFDC Deployments
Sujit Kumar
 
PPTX
SFDC Batch Apex
Sujit Kumar
 
PPTX
SFDC Data Loader
Sujit Kumar
 
PPTX
SFDC Advanced Apex
Sujit Kumar
 
PPTX
SFDC Introduction to Apex
Sujit Kumar
 
PPTX
SFDC Database Additional Features
Sujit Kumar
 
PPTX
Introduction to SalesForce
Sujit Kumar
 
PPTX
More about java strings - Immutability and String Pool
Sujit Kumar
 
PPTX
Hibernate First and Second level caches
Sujit Kumar
 
PPTX
Java Comparable and Comparator
Sujit Kumar
 
PPTX
Java build tools
Sujit Kumar
 
Introduction to OOP with java
Sujit Kumar
 
SFDC Database Basics
Sujit Kumar
 
SFDC Database Security
Sujit Kumar
 
SFDC Social Applications
Sujit Kumar
 
SFDC Other Platform Features
Sujit Kumar
 
SFDC Outbound Integrations
Sujit Kumar
 
SFDC Inbound Integrations
Sujit Kumar
 
SFDC UI - Advanced Visualforce
Sujit Kumar
 
SFDC UI - Introduction to Visualforce
Sujit Kumar
 
SFDC Deployments
Sujit Kumar
 
SFDC Batch Apex
Sujit Kumar
 
SFDC Data Loader
Sujit Kumar
 
SFDC Advanced Apex
Sujit Kumar
 
SFDC Introduction to Apex
Sujit Kumar
 
SFDC Database Additional Features
Sujit Kumar
 
Introduction to SalesForce
Sujit Kumar
 
More about java strings - Immutability and String Pool
Sujit Kumar
 
Hibernate First and Second level caches
Sujit Kumar
 
Java Comparable and Comparator
Sujit Kumar
 
Java build tools
Sujit Kumar
 
Ad

Recently uploaded (20)

PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 

Java equals hashCode Contract

  • 1. Java Equals HashCode Contract Sujit Kumar Zenolocity LLC © 2013-2023
  • 2. The Contract • 2 equal objects should have the same hashCode. • The reverse may or may not be true => 2 objects with the same hashCode may or may not be equal.
  • 3. Default implementations in Object class • The default implementation of hashCode() in Object class returns distinct integers for different objects. • The default implementation of equals() in Object class is reference equality, and therefore two instances are the same if and only if they are the same instance.
  • 4. Class with equals() but no hashCode() public class Banana { private String color; public Banana (String color) { this.color = color; } public boolean equals(Object obj) { if (!(obj instanceof Banana)) return false; if (obj == this) return true; return this.color.equals(((Banana) obj).color); } }
  • 5. equals() provided without hashCode() Banana a1 = new Banana("green"); Banana a2 = new Banana(“yellow”); //hashMap stores Banana type and its quantity HashMap<Banana, Integer> m = new HashMap<Banana, Integer>(); m.put(a1, 10); m.put(a2, 20); // Returns null even though the map contains a green Banana System.out.println(m.get(new Banana("green")));
  • 6. Add hashCode() method to Class public int hashCode() { return 29 * this.color.hashCode(); } // Returns the green Banana now ! System.out.println(m.get(new Banana("green")));
  • 7. Hash Collisions • put method – calculates the hashCode on the key and places the key-value pair in a bucket for that hashCode value. • The next put may result in the same hashCode if the hashCode method is not good enough to produce a unique value. This results in a hash collision. • Hash Collision results in multiple entries (k-v pairs) put in the same bucket in the form of a list. • When you retrieve using the get method, calculate the hashCode, go to the bucket & retrieve from the list in the bucket by invoking the equals method for each key in the list. • Hash Collisions degrade performance.
  • 8. Techniques to make a hashCode unique • Invoke the hashCode on each instance variable, multiply with a prime number like 29 and keep adding the results. • Return the final result.