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:
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.
p1.equals(p2) == true
set contains both p1 and p2?
Originally Posted by sunde887
Yes when I override only equals methods then two equal objects are added to set. But,when I override hashCode method,as you said in the post, objects aren't added.
Thanks once again
You are welcome, glad go have helped. Please mark your thread solved with the thread tools at the top of the page.