*
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
Author

HashSet Size

Shreya Jain
Greenhorn

Joined: Dec 21, 2009
Posts: 2

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

Joined: Feb 24, 2006
Posts: 6661
    
    5

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


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

Joined: Dec 21, 2009
Posts: 2
Thanks guys...
I understand this...its just because here equals and hashcode methods are not implemented..
 
Don't get me started about those stupid light bulbs.
 
subject: HashSet Size
 
Similar Threads
Wrappers with String and Collections
How is this printing 3, i have overridden the hashcode and equals method in here
Please explain the output
HashSet Duplicate element ?