aspose file tools*
The moose likes Java in General and the fly likes why they use hashCode() method in equals() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "why they use hashCode() method in equals() method " Watch "why they use hashCode() method in equals() method " New topic
Author

why they use hashCode() method in equals() method

naved momin
Ranch Hand

Joined: Jul 03, 2011
Posts: 692


in the example of equals operator in my sun certified book it was a code like below
but it prints the same output even though if we remove hashCode() method ...so then why they have used it over here
if they have used it that means is should have some specific task to perform
so what is that task ?
please explain



The Only way to learn is ...........do!
Visit my blog http://inaved-momin.blogspot.com/
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

And now use your objects in a HashMap. Whoops, that won't work - HashMap uses a combination of hashCode and equals to find keys.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
naved momin
Ranch Hand

Joined: Jul 03, 2011
Posts: 692

Rob Spoor wrote:And now use your objects in a HashMap. Whoops, that won't work - HashMap uses a combination of hashCode and equals to find keys.

thanks for the reply
i ddnt get you please use simple terms with there meaning i m not a oop champion , i m just a student
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Because e1 and e2 are equal, value should be "Hello World". It will be null however, because you haven't overridden hashCode(). As a result, the two equal objects e1 and e2 have different return values for hashCode(), and the Map gets all confused and returns the wrong result.

If you would now uncomment the hashCode() implementation it prints "Hello World" as expected.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why they use hashCode() method in equals() method