File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashSet issue 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 issue" Watch "HashSet issue" New topic

HashSet issue

luco zhao
Ranch Hand

Joined: Apr 23, 2002
Posts: 50
Hi there,
I've got a question about HashSet, first of all, please see my testing code, then I will give a short explaination of the problem.

As no duplicated elements allowed in Set, how to implement it? Thanks

Great thanks,<br />Luco Zhao
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
You have to implement hashCode() for Your class,
"Equal objects must have equal hashcodes"!
For hints on writing hashCode() method
have a look at chapter 3 of Bloch's book
"Effecitve Java":
Asif Mahmood

Joined: Jun 11, 2001
Posts: 29
Luco, apples.contains(apple2) would return false because you've not added apple2 object in the hash set.
apples.add(apple2) would definitely return true because apple2 object doesn't exists in hash set. apple2 object is different from apple object, although both of these objects are of the same class.
size of the set is 2. because you've added two different objects in this set. There is no duplication in set. But if you add the same apple2 object, or apple object once again, the size will remain 2. Because this time, you're adding same object more than once and set doesn't allow this.
Best regards,
Gautam Sewani
Ranch Hand

Joined: Apr 19, 2002
Posts: 93
Hi luco,
Your code is not resulting as expected,because,you have not implemented the hashCode() method.The default implementation of the hashCode() method,inherited from Object,simply returns new hashCodes for each new Object.So when HashSet adds apple objects ,it checks the hashCode of both the Objects,since on this occasion they are different,therefore both of them are added.
The equals method is only called when the Hashcode value of two objects is equal.
You can find this by placing a println statement in the equals method of the println class.
I hope that helps.
Best regards
I agree. Here's the link:
subject: HashSet issue
jQuery in Action, 3rd edition