Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet issue

 
luco zhao
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic