Results 1 to 4 of 4
  1. #1
    Anveshan is offline Member
    Join Date
    May 2011
    Posts
    24
    Rep Power
    0

    Unhappy 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:

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    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?
    Java Code:
    p1.equals(p2)  == true
    
    and 
    set contains both p1 and p2?
    If so I believe you may want to override hashcode and see what happens.

  3. #3
    Anveshan is offline Member
    Join Date
    May 2011
    Posts
    24
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    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?
    Java Code:
    p1.equals(p2)  == true
    
    and 
    set contains both p1 and p2?
    If so I believe you may want to override hashcode and see what happens.
    Thanks 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

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You are welcome, glad go have helped. Please mark your thread solved with the thread tools at the top of the page.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •