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

HashSet Size

 
Shreya Jain
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi,
Anybody please help me in understanding "How exactly insertion in set happens?"




Why size is coming 3 ?As I am expecting it 2.

 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to javaranch.

Why did you expect the answer 2 ?

Hint: Does your class define an equals method ?
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To give you a HINT: print the contents of HashSet and see for yourself what are the 3 elements!
also java.lang.String overrides hashCode() and equals() ; where as your class HashTest{} doesn't do that!

 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question was already discussed, have a Google search!
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You must remember that to the Set Interface replace identicals objects, the classes must override the equals/hashCode methods.

At your sample, notice that String class has equals/hashCode already overrided. The hashTest doenst.

C ya
 
Shreya Jain
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys...
I understand this...its just because here equals and hashcode methods are not implemented..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic