• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

TreeMap vs HashMap

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anyone please tell me why in this program; I can retrieve "A" value from TreeMap but not HashMap.

It returns null value with HashMap.

Is there anyway that I can fix it?

Thanks

---------------------------Result---------------------------------
A says - I am A
A says - null

[I added [code] tags - Jim]
[ September 06, 2005: Message edited by: Jim Yingst ]
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

HashMap uses the hashCode() method, and expects it to return values "consistent with equals()". What this means is that if you override equals() for a class, you always need to override hashCode() as well, so that two objects that are equal() will have the same hashCode() return value.

In your case, an excellent implementation would just delegate to "name" -- i.e.,



Since your equals() method is also based solely on the "name" member, this will do the exactly right thing.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

This is a subtle but serious problem. You have not overridden the equals(Object) method here - you have merely overloaded it.
 
Ernest Friedman-Hill
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Yingst:

This is a subtle but serious problem.



Good eye! Thanks, Jim.
 
Raymond Fung
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks guys!!!

It works now
 
Just let me do the talking. Ahem ... so ... you see ... we have this tiny ad...
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic