This week's book giveaway is in the Cloud/Virtualization forum.
We're giving away four copies of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds and have James Denton on-line!
See this thread for details.
Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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

 
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • 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

 
Sheriff
Posts: 21453
96
Chrome Eclipse IDE Java Windows
  • 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
  • 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
Posts: 21453
96
Chrome Eclipse IDE Java Windows
  • 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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!