SlideShare a Scribd company logo
Why always override hashcode() if overriding
equals()?
In Java, every object has access to the equals() method because it is inherited from the Object class.
However, this default implementation just simply compares the memory addresses of the objects. You
can override the default implementation of the equals() method defined in java.lang.Object. If you
override the equals(), you MUST also override hashCode(). Otherwise a violation of the general
contract for Object.hashCode will occur, which can have unexpected repercussions when your class is
in conjunction with all hash-based collections.

public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as
those provided by java.util.Hashtable.
The general contract of hashCode is:

    • Whenever it is invoked on the same object more than once during an execution of a Java
      application, the hashCode method must consistently return the same integer, provided no
      information used in equals comparisons on the object is modified. This integer need not remain
      consistent from one execution of an application to another execution of the same application.
    • If two objects are equal according to the equals(Object) method, then calling the hashCode
      method on each of the two objects must produce the same integer result.
    • It is not required that if two objects are unequal according to the equals(java.lang.Object)
      method, then calling the hashCode method on each of the two objects must produce distinct
      integer results. However, the programmer should be aware that producing distinct integer results
      for unequal objects may improve the performance of hashtables.
The default implementation of equals() method checks to see if the two objects have the same identity.
Similarly, the default implementation of the hashCode() method returns an integer based on the object's
identity and is not based on the values of instance (and class) variables of the object. No matter how
many times the values of its instance variables (data fields) change, the hash code calculated by the
default hashCode implementation does not change during the life of the object.


Consider the following code, we have overridden equals() method to check if two objects are equal
based on the values of their instance variables. Two objects may be stored at different memory
addresses but may still be equal base on their instance variable.
public class CustomerID {
  private long crmID;
  private int nameSpace;
  public CustomerID(long crmID, int nameSpace) {
    super();
    this.crmID = crmID;
    this.nameSpace = nameSpace;
  }
  public boolean equals(Object obj) {
    //null instanceof Object will always return false
if (!(obj instanceof CustomerID))
       return false;
     if (obj == this)
       return true;
     return this.crmID == ((CustomerID) obj).crmID &&
             this.nameSpace == ((CustomerID) obj).nameSpace;
    }
    public static void main(String[] args) {
      Map m = new HashMap();
      m.put(new CustomerID(2345891234L,0),"Jeff Smith");
      System.out.println(m.get(new CustomerID(2345891234L,0)));
    }
}

Compile and run the above code, the output result is
null

What is wrong? The two instances of CustomerID are logically equal according to the class's equals
method. Because the hashCode() method is not overridden, these two instances' identities are not in
common to the default hashCode implementation. Therefore, the Object.hashCode returns two
seemingly random numbers instead of two equal numbers. Such behavior violates "Equal objects must
have equal hash codes" rule defined in the hashCode contract.
Let's provide a simple hashCode() method to fix this problem:
public class CustomerID {
  private long crmID;
  private int nameSpace;
  public CustomerID(long crmID, int nameSpace) {
    super();
    this.crmID = crmID;
    this.nameSpace = nameSpace;
  }
  public boolean equals(Object obj) {
    //null instanceof Object will always return false
    if (!(obj instanceof CustomerID))
      return false;
    if (obj == this)
      return true;
    return this.crmID == ((CustomerID) obj).crmID &&
             this.nameSpace == ((CustomerID) obj).nameSpace;
  }
  public int hashCode() {
    int result = 0;
    result = (int)(crmID/12) + nameSpace;
    return result;
  }
  public static void main(String[] args) {
    Map m = new HashMap();
    m.put(new CustomerID(2345891234L,0),"Jeff Smith");
    System.out.println(m.get(new CustomerID(2345891234L,0)));
  }
}

Compile and run the above code, the output result is
Jeff Smith
The hashcode distribution for instances of a class should be random. This is exactly what is meant by
the third provision of the hashCode contract. Write a correct hashCode method is easy, but to write an
effective hashCode method is extremely difficult.




What is the difference between JDK and JRE?
The JRE is the Java RunTime Environment that is a plug-in needed for running java programs. The
JRE is an implementation of the Java Virtual Machine which actually executes Java programs.
The JDK is the Java Development Kit for Java application developers. The JDK is bundle of software
which contains one (or more) JRE's along with the various development tools like the Java source
compilers, bundling and deployment tools, debuggers, development libraries, etc.




Can we Override the Start()?
Public Sync

More Related Content

PPT
JavaScript Objects
PPT
Covariance, contravariance 觀念分享
PPTX
Joshua bloch effect java chapter 3
PDF
JavaScript: Patterns, Part 2
PDF
JavaScript - Chapter 4 - Types and Statements
PPT
An introduction to javascript
PDF
Introduction to JQ
PDF
javascript objects
JavaScript Objects
Covariance, contravariance 觀念分享
Joshua bloch effect java chapter 3
JavaScript: Patterns, Part 2
JavaScript - Chapter 4 - Types and Statements
An introduction to javascript
Introduction to JQ
javascript objects

What's hot (20)

PPTX
mediator
PDF
Implicit conversion and parameters
PPT
Advanced Javascript
PDF
jq: JSON - Like a Boss
DOCX
Diifeerences In C#
ODP
Pattern Matching - at a glance
PPTX
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
PPT
Create and analyse programs
PDF
3.1 javascript objects_DOM
PDF
JavaScript - Chapter 6 - Basic Functions
PPT
Synapseindia strcture of dotnet development part 2
PDF
What is new on ES6
DOCX
Memory management in c++
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
PPT
PPTX
Java best practices
PPTX
Object Oriented JavaScript
PPTX
Constructors and Destructors
PDF
The Ring programming language version 1.5.2 book - Part 70 of 181
PDF
Grid gain paper
mediator
Implicit conversion and parameters
Advanced Javascript
jq: JSON - Like a Boss
Diifeerences In C#
Pattern Matching - at a glance
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Create and analyse programs
3.1 javascript objects_DOM
JavaScript - Chapter 6 - Basic Functions
Synapseindia strcture of dotnet development part 2
What is new on ES6
Memory management in c++
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
Java best practices
Object Oriented JavaScript
Constructors and Destructors
The Ring programming language version 1.5.2 book - Part 70 of 181
Grid gain paper
Ad

Similar to Java%20 new%20faq.doc 0 (20)

DOCX
Core Java Equals and hash code
PPTX
Java equals hashCode Contract
PPSX
PPTX
Methods common to all objects
PPT
Oop lecture9 13
PPTX
javaimplementation
PDF
Java Day-4
PPTX
Java tutorial part 4
PDF
Java puzzle-1195101951317606-3
KEY
ぐだ生 Java入門第一回(equals hash code_tostring)
PDF
First Among Equals
PDF
Java Puzzle
PPTX
4Unit - 2 The Object Class.pptx
PDF
Java Class Design
PDF
Overriding methods
ZIP
Hashing
PPTX
Effective Java - Chapter 3: Methods Common to All Objects
PPTX
Object Class
PPTX
Javasession7
PPT
Effective Java - Methods Common to All Objects
Core Java Equals and hash code
Java equals hashCode Contract
Methods common to all objects
Oop lecture9 13
javaimplementation
Java Day-4
Java tutorial part 4
Java puzzle-1195101951317606-3
ぐだ生 Java入門第一回(equals hash code_tostring)
First Among Equals
Java Puzzle
4Unit - 2 The Object Class.pptx
Java Class Design
Overriding methods
Hashing
Effective Java - Chapter 3: Methods Common to All Objects
Object Class
Javasession7
Effective Java - Methods Common to All Objects
Ad

Recently uploaded (20)

PPTX
Lesson notes of climatology university.
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Complications of Minimal Access Surgery at WLH
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
master seminar digital applications in india
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Lesson notes of climatology university.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Module 4: Burden of Disease Tutorial Slides S2 2025
Microbial disease of the cardiovascular and lymphatic systems
Abdominal Access Techniques with Prof. Dr. R K Mishra
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Complications of Minimal Access Surgery at WLH
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
master seminar digital applications in india
Final Presentation General Medicine 03-08-2024.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Final Presentation General Medicine 03-08-2024.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
A systematic review of self-coping strategies used by university students to ...
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
GDM (1) (1).pptx small presentation for students
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...

Java%20 new%20faq.doc 0

  • 1. Why always override hashcode() if overriding equals()? In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object. If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections. public int hashCode() Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. The general contract of hashCode is: • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. The default implementation of equals() method checks to see if the two objects have the same identity. Similarly, the default implementation of the hashCode() method returns an integer based on the object's identity and is not based on the values of instance (and class) variables of the object. No matter how many times the values of its instance variables (data fields) change, the hash code calculated by the default hashCode implementation does not change during the life of the object. Consider the following code, we have overridden equals() method to check if two objects are equal based on the values of their instance variables. Two objects may be stored at different memory addresses but may still be equal base on their instance variable. public class CustomerID { private long crmID; private int nameSpace; public CustomerID(long crmID, int nameSpace) { super(); this.crmID = crmID; this.nameSpace = nameSpace; } public boolean equals(Object obj) { //null instanceof Object will always return false
  • 2. if (!(obj instanceof CustomerID)) return false; if (obj == this) return true; return this.crmID == ((CustomerID) obj).crmID && this.nameSpace == ((CustomerID) obj).nameSpace; } public static void main(String[] args) { Map m = new HashMap(); m.put(new CustomerID(2345891234L,0),"Jeff Smith"); System.out.println(m.get(new CustomerID(2345891234L,0))); } } Compile and run the above code, the output result is null What is wrong? The two instances of CustomerID are logically equal according to the class's equals method. Because the hashCode() method is not overridden, these two instances' identities are not in common to the default hashCode implementation. Therefore, the Object.hashCode returns two seemingly random numbers instead of two equal numbers. Such behavior violates "Equal objects must have equal hash codes" rule defined in the hashCode contract. Let's provide a simple hashCode() method to fix this problem: public class CustomerID { private long crmID; private int nameSpace; public CustomerID(long crmID, int nameSpace) { super(); this.crmID = crmID; this.nameSpace = nameSpace; } public boolean equals(Object obj) { //null instanceof Object will always return false if (!(obj instanceof CustomerID)) return false; if (obj == this) return true; return this.crmID == ((CustomerID) obj).crmID && this.nameSpace == ((CustomerID) obj).nameSpace; } public int hashCode() { int result = 0; result = (int)(crmID/12) + nameSpace; return result; } public static void main(String[] args) { Map m = new HashMap(); m.put(new CustomerID(2345891234L,0),"Jeff Smith"); System.out.println(m.get(new CustomerID(2345891234L,0))); } } Compile and run the above code, the output result is Jeff Smith
  • 3. The hashcode distribution for instances of a class should be random. This is exactly what is meant by the third provision of the hashCode contract. Write a correct hashCode method is easy, but to write an effective hashCode method is extremely difficult. What is the difference between JDK and JRE? The JRE is the Java RunTime Environment that is a plug-in needed for running java programs. The JRE is an implementation of the Java Virtual Machine which actually executes Java programs. The JDK is the Java Development Kit for Java application developers. The JDK is bundle of software which contains one (or more) JRE's along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc. Can we Override the Start()? Public Sync