Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashMap entries with duplicate keys...

 
Jigs Gohil
Greenhorn
Posts: 6
Eclipse IDE jQuery Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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




Thanks...
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello J World ?

and welcome to JavaRanch .
 
Jigar Gohil
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jigar Gohil wrote:
What about the default implementation of hashcode...?


@see java.lang.Object#hashCode
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic