Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashSet Size Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashSet Size" Watch "HashSet Size" New topic

HashSet Size

Shreya Jain

Joined: Dec 21, 2009
Posts: 2

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

Joined: Feb 24, 2006
Posts: 6662

Welcome to javaranch.

Why did you expect the answer 2 ?

Hint: Does your class define an equals method ?

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Rajeev Rnair
Ranch Hand

Joined: Mar 22, 2010
Posts: 308

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!

SCJP6, SCWCD5, OCP-JBCD5, OCE-JWSD6 OCE-JPAD6 , OCM-JEA5 1,OCM-JEA5 2,3 - Brainbench certifications: J2EE, Java2, Java2-NonGUI, JSP, SQL2000 Admin, SQL2000 Programming , Brainbench certified Java Programmer, Computer Programmer, Web Developer, Database Administrator
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Question was already discussed, have a Google search!

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Hebert Coelho
Ranch Hand

Joined: Jul 14, 2010
Posts: 754

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

[] [Full WebApplication JSF EJB JPA JAAS with source code to download] One Table Per SubClass [Web/JSF]
Shreya Jain

Joined: Dec 21, 2009
Posts: 2
Thanks guys...
I understand this...its just because here equals and hashcode methods are not implemented..
I agree. Here's the link:
subject: HashSet Size
It's not a secret anymore!