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
PDF
High-Performance Haskell
PPTX
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
PPTX
5 of the Limit Laws
ZIP
Hashing
PPTX
Rehashing
PDF
List , tuples, dictionaries and regular expressions in python
PPT
Object Range
Functional ruby
High-Performance Haskell
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
5 of the Limit Laws
Hashing
Rehashing
List , tuples, dictionaries and regular expressions in python
Object Range

What's hot (20)

PPTX
16 containers
PDF
Python tuple
PDF
Hashtable
PPTX
Regular Expressions in JavaScript and Command Line
PPTX
Quadratic probing
PDF
Python Workshop Part 2. LUG Maniapl
PPT
Hashing gt1
PDF
Python List Comprehensions
PDF
Using Affordance for Clearer Source Code
PDF
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
PPT
Hashing PPT
PPTX
Hashing data
PPTX
List in Python
PPT
18 hashing
PPT
Data Structure and Algorithms Hashing
PPT
Hashing
PDF
Color picker2
PPTX
Statistics - ArgMax Equation
PPTX
Hashing
16 containers
Python tuple
Hashtable
Regular Expressions in JavaScript and Command Line
Quadratic probing
Python Workshop Part 2. LUG Maniapl
Hashing gt1
Python List Comprehensions
Using Affordance for Clearer Source Code
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing PPT
Hashing data
List in Python
18 hashing
Data Structure and Algorithms Hashing
Hashing
Color picker2
Statistics - ArgMax Equation
Hashing
Ad

Similar to Java equals hashCode Contract (12)

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

More from Sujit Kumar (20)

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

Recently uploaded (20)

PPTX
A Presentation on Artificial Intelligence
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Machine Learning_overview_presentation.pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Tartificialntelligence_presentation.pptx
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Getting Started with Data Integration: FME Form 101
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Electronic commerce courselecture one. Pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
A Presentation on Artificial Intelligence
Group 1 Presentation -Planning and Decision Making .pptx
Big Data Technologies - Introduction.pptx
Machine Learning_overview_presentation.pptx
A comparative analysis of optical character recognition models for extracting...
Reach Out and Touch Someone: Haptics and Empathic Computing
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Unlocking AI with Model Context Protocol (MCP)
Tartificialntelligence_presentation.pptx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Spectroscopy.pptx food analysis technology
Per capita expenditure prediction using model stacking based on satellite ima...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Getting Started with Data Integration: FME Form 101
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Encapsulation theory and applications.pdf
Programs and apps: productivity, graphics, security and other tools
Electronic commerce courselecture one. Pdf
MIND Revenue Release Quarter 2 2025 Press Release
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

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.