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

KEY
Functional ruby
Kerry Buckley
 
PDF
High-Performance Haskell
Johan Tibell
 
PPTX
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
Meghaj Mallick
 
PPTX
5 of the Limit Laws
Trisha Ababa
 
ZIP
Hashing
Sri Prasanna
 
PPTX
Rehashing
rajshreemuthiah
 
PDF
List , tuples, dictionaries and regular expressions in python
channa basava
 
PPT
Object Range
mussawir20
 
Functional ruby
Kerry Buckley
 
High-Performance Haskell
Johan Tibell
 
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
Meghaj Mallick
 
5 of the Limit Laws
Trisha Ababa
 
Hashing
Sri Prasanna
 
Rehashing
rajshreemuthiah
 
List , tuples, dictionaries and regular expressions in python
channa basava
 
Object Range
mussawir20
 

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
 
Ad

Similar to Java equals hashCode Contract (10)

ODT
Java%20 new%20faq.doc 0
aravind_aashu
 
DOCX
Core Java Equals and hash code
mhtspvtltd
 
PPSX
Ejp 01
Md. Fasihul Kabir
 
PPTX
Joshua bloch effect java chapter 3
Kamal Mukkamala
 
PPTX
Methods common to all objects
Sandeep Chawla
 
KEY
ぐだ生 Java入門第一回(equals hash code_tostring)
Makoto Yamazaki
 
PDF
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
PPTX
Object Class
RatnaJava
 
PPTX
javaimplementation
FaRaz Ahmad
 
PPT
Oop lecture9 13
Shahriar Robbani
 
Java%20 new%20faq.doc 0
aravind_aashu
 
Core Java Equals and hash code
mhtspvtltd
 
Joshua bloch effect java chapter 3
Kamal Mukkamala
 
Methods common to all objects
Sandeep Chawla
 
ぐだ生 Java入門第一回(equals hash code_tostring)
Makoto Yamazaki
 
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
Object Class
RatnaJava
 
javaimplementation
FaRaz Ahmad
 
Oop lecture9 13
Shahriar Robbani
 
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
 

Recently uploaded (20)

PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
Software Development Company | KodekX
KodekX
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
DOCX
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Software Development Company | KodekX
KodekX
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
This slide provides an overview Technology
mineshkharadi333
 
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Doc9.....................................
SofiaCollazos
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
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.