File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
naved momin
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

 
Rob Spoor
Sheriff
Pie
Posts: 20388
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And now use your objects in a HashMap. Whoops, that won't work - HashMap uses a combination of hashCode and equals to find keys.
 
naved momin
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20388
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic