wood burning stoves 2.0*
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
Author

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
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
You have to implement hashCode() for Your class,
because
"Equal objects must have equal hashcodes"!
For hints on writing hashCode() method
have a look at chapter 3 of Bloch's book
"Effecitve Java":
http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf
Regards
Asif Mahmood
Greenhorn

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,
-Asif
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
Gautam
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashSet issue