• 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
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Bear Bibeault
  • paul wheaton
Saloon Keepers:
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Mikalai Zaikin
  • Piet Souris
Bartenders:

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
 
Won't you be my neighbor? - Fred Rogers. tiny ad:
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
reply
    Bookmark Topic Watch Topic
  • New Topic