Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

equals() & hashCode()

 
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What happens if I override the equals() method but do not override the hashCode() if I am using the following class as a key in a hashmap? What will be the impact on performance while I perform a searching assuing that the HashMap has a milion entrie?

class MyKey{
int i;
boolean equals(Object obj){
if (obj == null)
return false;
if (obj == this)
return true;
return (((MyKey)obj).i == this.i);
}
 
author and iconoclast
Posts: 24203
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The impact on performance will be that it won't work. If hashCode() and equals() don't agree, it will be impossible to find many keys in the map.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For this code, an appropriate hashCode() is very simple anyway, since the equals depends only on i:

For discussion of hashCode() for more complex classes (and many other useful issues), I recommend Effective Java.
 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you override equals method, you are deciding as to in what cases you say two objects of your class as equal. If you decide that two objects are equal then hashcode must be equal. we cannot have the same guy at different places simultaneously right.
 
reply
    Bookmark Topic Watch Topic
  • New Topic