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

What's hot

mediator
mediatormediator
mediator
guest55ff01
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
relay12
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
rohit_gupta_mrt
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
Knoldus Inc.
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Abu Saleh
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
Dr. C.V. Suresh Babu
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2
Synapseindiappsdevelopment
 
What is new on ES6
What is new on ES6What is new on ES6
What is new on ES6
Huge
 
Memory management in c++
Memory management in c++Memory management in c++
Memory management in c++
Syed Hassan Kazmi
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Java 7
Java 7Java 7
Java best practices
Java best practicesJava best practices
Java best practices
Անուշիկ Միրզոյան
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
injulkarnilesh
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181
Mahmoud Samir Fayed
 
Grid gain paper
Grid gain paperGrid gain paper
Grid gain paper
SubhashiniSukumar
 

What's hot (20)

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

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

Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
Sujit Kumar
 
Methods common to all objects
Methods common to all objectsMethods common to all objects
Methods common to all objects
Sandeep Chawla
 
Core Java Equals and hash code
Core Java Equals and hash codeCore Java Equals and hash code
Core Java Equals and hash code
mhtspvtltd
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
FaRaz Ahmad
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
Carol McDonald
 
Analyzing Firebird 3.0
Analyzing Firebird 3.0Analyzing Firebird 3.0
Analyzing Firebird 3.0
Ekaterina Milovidova
 
Analyzing Firebird 3.0
Analyzing Firebird 3.0Analyzing Firebird 3.0
Analyzing Firebird 3.0
PVS-Studio
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
anjani pavan kumar
 
Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2
Empatika
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
fashionscollect
 
Javascript
JavascriptJavascript
Javascript
Gita Kriz
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
PVS-Studio
 
JPA 2.0
JPA 2.0JPA 2.0
Still Comparing "this" Pointer to Null?
Still Comparing "this" Pointer to Null?Still Comparing "this" Pointer to Null?
Still Comparing "this" Pointer to Null?
Andrey Karpov
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
People Strategists
 
Collections
CollectionsCollections
Collections
sagsharma
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
C++ Homework Help
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScripts
Anton Astashov
 
CS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReportCS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReport
Akshay Mittal
 

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

Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
 
Methods common to all objects
Methods common to all objectsMethods common to all objects
Methods common to all objects
 
Core Java Equals and hash code
Core Java Equals and hash codeCore Java Equals and hash code
Core Java Equals and hash code
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
Analyzing Firebird 3.0
Analyzing Firebird 3.0Analyzing Firebird 3.0
Analyzing Firebird 3.0
 
Analyzing Firebird 3.0
Analyzing Firebird 3.0Analyzing Firebird 3.0
Analyzing Firebird 3.0
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
 
Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
 
Javascript
JavascriptJavascript
Javascript
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 
Still Comparing "this" Pointer to Null?
Still Comparing "this" Pointer to Null?Still Comparing "this" Pointer to Null?
Still Comparing "this" Pointer to Null?
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Collections
CollectionsCollections
Collections
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScripts
 
CS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReportCS5393-Korat_Mittal_Akshay_ProjReport
CS5393-Korat_Mittal_Akshay_ProjReport
 

Recently uploaded

A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
OH TEIK BIN
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 
How to Setup Default Value for a Field in Odoo 17
How to Setup Default Value for a Field in Odoo 17How to Setup Default Value for a Field in Odoo 17
How to Setup Default Value for a Field in Odoo 17
Celine George
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
zuzanka
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
 
Observational Learning
Observational Learning Observational Learning
Observational Learning
sanamushtaq922
 
How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17
Celine George
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
Iris Thiele Isip-Tan
 
How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17
Celine George
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
Kalna College
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
Nguyen Thanh Tu Collection
 
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.pptLevel 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Henry Hollis
 
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
TechSoup
 
How to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in useHow to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in use
Celine George
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.
IsmaelVazquez38
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapitolTechU
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
Kalna College
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
Kalna College
 

Recently uploaded (20)

A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 
How to Setup Default Value for a Field in Odoo 17
How to Setup Default Value for a Field in Odoo 17How to Setup Default Value for a Field in Odoo 17
How to Setup Default Value for a Field in Odoo 17
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
 
Observational Learning
Observational Learning Observational Learning
Observational Learning
 
How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
 
How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
 
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN TẬP VÀ PHÁT TRIỂN CÂU HỎI TRONG ĐỀ MINH HỌA THI TỐT NGHIỆP THPT ...
 
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.pptLevel 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
 
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
 
How to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in useHow to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in use
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.Bossa N’ Roll Records by Ismael Vazquez.
Bossa N’ Roll Records by Ismael Vazquez.
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
 

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