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

Question on HashSet

 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


output :
Set contains --5
Set contains --5
Set contains --3

Why its returning me tow times 5 , i have used the equals and hashcode also.
Can anyone help me out ..

 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to override hashCode() method (with capital C).
 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry my mistake:

Thanks for correcting.

If i pass null set.put(null), it gives me NullPointer Expection, i know nullponter means its trying to refer th object with null reference in memory.
Correct me if iam wrong
 
bart zagers
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you want '||' in your equals method instead of '&&'.

You get the NullPointerException on the line
System.out.println("Set contains --" + t.count);
You get null from the Set, so t == null, so t.count gives you the exception.
So you don't get the exception in the setting, but in the getting
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic