aspose file tools
The moose likes Beginning Java and the fly likes equals() & hashCode() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "equals() & hashCode()" Watch "equals() & hashCode()" New topic
Author

equals() & hashCode()

Santosh Pasupuleti
Ranch Hand

Joined: Aug 10, 2005
Posts: 97
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);
}
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24081
    
  15

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.


[Jess in Action][AskingGoodQuestions]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18670
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.


"I'm not back." - Bill Harding, Twister
Chetan Raju
Ranch Hand

Joined: Aug 02, 2006
Posts: 109
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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: equals() & hashCode()
 
Similar Threads
HashCode and Equals
can you please this doubt about hashcode()
Key in the HashMap.
Map and Set
hashmap