This content has been marked as final. Show 4 replies
Prem wrote:No, it doesn't work that way, and it won't be helpful. Just doing your work for you doesn't help you. The idea is to give you the tools to solve your own problem--to nudge you just enough to get you over the hump. You still have to do the hard work, and the boring, tedious work as well.
jtahlborn wrote:Could you please elaborate more by editing my code.... It will be very helpful.
equality for a HashSet is controlled via the hashCode() and equals() methods on the objects you add to it. make sure yours are implemented appropriately.
You need to take a step back and think for a bit.
You know that a Set will not allow two elements that are equal by the equals() method. You say that you want to add two elements that have "the same values". So according to your business logic, are those two objects "equal"? If so, then why are you using a Set in the first place? If they're not "equal" according to your business logic, then your equals() method should not just blindly compare all their fields. That's a common equals() approach, but there's no law that says equals() has to be written that way.
1) What does it mean for two of your objects to be equal? Write equals() to match that.
2) If you want to insert two objects that are "equal" by the above into a collection, then, by definition, a Set is not appropriate here.
If you want more info on implementing equals and hashcode, see here: http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf or google for examples.