wood burning stoves 2.0*
The moose likes Java in General and the fly likes HashMap entries with duplicate keys... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "HashMap entries with duplicate keys..." Watch "HashMap entries with duplicate keys..." New topic
Author

HashMap entries with duplicate keys...

Jigs Gohil
Greenhorn

Joined: Jun 09, 2011
Posts: 6


Hi, In spite of overriding equals, why HashMap is allowing duplicate entries...?




Thanks...
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Hello J World wrote:
Hi, In spite of overriding equals, why HashMap is allowing duplicate entries...?


you should override hashCode method too. because HashMap entry checks the equality of both hashCode and equals . if any one fails then HashMap add the new entry value. @see HashMap#put(K, V)

<edit> also your overridden equals method can be fragile . have a look how to override an equals method</edit>
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Hello J World ?

and welcome to JavaRanch .
Jigar Gohil
Greenhorn

Joined: Dec 04, 2008
Posts: 11
Seetharaman Venkatasamy wrote:
Hello J World wrote:
Hi, In spite of overriding equals, why HashMap is allowing duplicate entries...?


you should override hashCode method too. because HashMap entry checks the equality of both hashCode and equals . if any one fails then HashMap add the new entry value. @see HashMap#put(K, V)

<edit> also your overridden equals method can be fragile . have a look how to override an equals method</edit>


yaa..I know i must apply instatnceof check as well...but
What about the default implementation of hashcode...?
As per my understanding it puts all the elements in a single bucket...doesn't it...?


Thanks...
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Jigar Gohil wrote:
What about the default implementation of hashcode...?


@see java.lang.Object#hashCode
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

No it doesn't. It's more likely to put all objects in different buckets. But you really should read the Javadoc comments of Object.equals and Object.hashCode. They explain you exactly which rules you must follow if you override one or both.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashMap entries with duplicate keys...