Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why am I being able to add Duplicates to this set?

 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How Am I being able to add these two duplicate objects to the set?. also can someone help me fix the iterator so i can go thru what I have added.
thanks
 
Vinayagar Karpagam
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think SetExample has to override equals() method so that the contents are compared.

try adding this :

 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey thanks man. Im only a few days away from exam and in my anxiety im forgetting my basics.

as for my second question to get the iterator to work toString() must be overriden.

Thanks both of you.
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if instead you make:
SetExample s2=s1;
your output will be: 1

EDITED
but, even using your code with that equals(), output still is 2, because those two String Objects are in fact two diferent objects (diferent memory locations, i guess)
anyway i think Equals() is incomplete
[ August 13, 2006: Message edited by: miguel lisboa ]
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you also have to override hashCode:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic