Results 1 to 4 of 4
Thread: Help me with Set
- 05-02-2011, 07:50 AM #1
Member
- Join Date
- May 2011
- Posts
- 22
- Rep Power
- 0
Help me with Set
I am new to java.. Plesae help with this .
Sets doesn't have dulicates by definition. So if I add two equals (for ex :"Hello")stings, only first time it gets added and second returns false(by add()) and doesn't add. But what happens when I try to add two objects (say Person having "name" and "age" as attributes) ? When I create two Person objects with say same name and age , and add it to set(hashset) and I am seeing both objects added to set(I have defined equals method in the Person). How can I prevent addition of two equal objects in the set ?
Can anybody help me ? PLease excuse me if I am not talking sense ...:confused:
- 05-02-2011, 07:56 AM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
So you are saying you are able to add two people who are equal according to the method equals, and both are in the Set?
If so I believe you may want to override hashcode and see what happens.Java Code:p1.equals(p2) == true and set contains both p1 and p2?
- 05-02-2011, 08:17 AM #3
Member
- Join Date
- May 2011
- Posts
- 22
- Rep Power
- 0
- 05-02-2011, 08:48 AM #4
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
You are welcome, glad go have helped. Please mark your thread solved with the thread tools at the top of the page.


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks