• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic