• Post Reply Bookmark Topic Watch Topic
  • New Topic

TreeMap vs HashMap  RSS feed

 
Raymond Fung
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • 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 ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • 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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks guys!!!

It works now
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!