Page 1 of 2 12 LastLast
Results 1 to 20 of 25
Like Tree1Likes

Thread: HashSet accept duplicated Value

  1. #1
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default HashSet accept duplicated Value

    Hello;

    as known HashSet store no duplicated values Unlike ArrayList, anyway i tried to make example to store Objects in HashSet and the result show it take Duplicated values

    Java Code:
    import java.util.Comparator;
    
    public class Employee{
        
        private int id;
        private String name;
        private String address;
        private double salary;
    
        public Employee(int id, String name, String address, double salary) {
            this.id = id;
            this.name = name;
            this.address = address;
            this.salary = salary;
        }
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public double getSalary() {
            return salary;
        }
    
        public void setSalary(double salary) {
            this.salary = salary;
        }
        
        public String toString(){
            return "ID:" + getId() + ", Name:" + getName() + ", Address:" + getAddress() + ", Salary:" + getSalary();
        }
                }
    create Objects and add them to Set and List
    Java Code:
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Set;
    
    
    public class Main {
        
        public static void main(String args[]) {
            Employee ts1 = new Employee (10, "Sam", "Paris", 200.0);
            Employee ts2 = new Employee (11, "Amal", "Berlin", 600.0);
            Employee ts3 = new Employee (12, "Nik", "London", 250.0);
            Employee ts4 = new Employee (10, "Sam", "Paris", 200.0);
            Employee ts5 = new Employee (14, "Jasmin", "Damas", 210.0);
           
            ArrayList<Employee> list = new ArrayList<Employee>();
        
            list.add(ts1);
            list.add(ts2);
            list.add(ts3);
            list.add(ts4);
            list.add(ts5);
            
            System.out.println("List");
            System.out.println("===================================================");
            for (int i = 0; i < list.size(); i++){
                System.out.println(list.get(i));
            }
            
            Set<Employee> set = new HashSet<Employee>();
            
            set.add(ts1);
            set.add(ts2);
            set.add(ts3);
            set.add(ts4);
            set.add(ts5);
            
            System.out.println("");
            System.out.println("Set");
            System.out.println("===================================================");
        for(Employee item: set){
             System.out.println(item);
        }
        }
    }
    Output:
    Java Code:
    List
    ===================================================
    ID:10, Name:Sam, Address:Paris, Salary:200.0
    ID:11, Name:Amal, Address:Berlin, Salary:600.0
    ID:12, Name:Nik, Address:Lndon, Salary:250.0
    ID:10, Name:Sam, Address:Paris, Salary:200.0
    ID:14, Name:Jasmin, Address:Damas, Salary:210.0
    
    Set
    ===================================================
    ID:12, Name:Nik, Address:London, Salary:250.0
    ID:10, Name:Sam, Address:Paris, Salary:200.0
    ID:14, Name:Jasmin, Address:Damas, Salary:210.0
    ID:10, Name:Sam, Address:Paris, Salary:200.0
    ID:11, Name:Amal, Address:Berlin, Salary:600.0
    The same result but not the same Order, anyway how to make Hashset in this code be able to not take any duplicated Value??

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,455
    Rep Power
    20

    Default Re: HashSet accept duplicated Value

    No, they're not duplicated objects. Have you read the documentation for the Set interface?
    sets contain no pair of elements e1 and e2 such that e1.equals(e2)
    In your example code, for which two elements would e1.equals(e2)?

    You need to override the equals(...) method and also override hashCode() to fulfill the contract laid out in the documentation for Object.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: HashSet accept duplicated Value

    I do recommend reading the links given to you in the link below. You've cross-posted just about every question you've asked without providing any reference to said crosspost. I can only speak for myself, but its not encouraging me to help

    Cross-posted at HashSet store duplicated Value
    Last edited by doWhile; 08-02-2013 at 07:46 PM.

  4. #4
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default Re: HashSet accept duplicated Value

    You need to override the equals(...) method and also override hashCode() to fulfill the contract laid out in the documentation for Object.
    can you give me example to do it or some link to read how to make it because it is very urgent

    thanks

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,728
    Blog Entries
    7
    Rep Power
    21

    Default Re: HashSet accept duplicated Value

    Quote Originally Posted by vector_ever View Post
    can you give me example to do it or some link to read how to make it because it is very urgent

    thanks
    I'll spoonfeed you with the hash code for an employee class:

    Java Code:
    public int hashCode() {
       return id ^ name.hashCode() ^ address.hashCode() ^ ((int)salary);
    }
    This example didn't help you one bit, all you can do is copy and paste it and see that it works. For the equals( ... ) method you have to do some thinking for yourself: let a and b be two Employee objects; when do you consider them equal?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default Re: HashSet accept duplicated Value

    I'll spoonfeed you with the hash code for an employee class:

    public int hashCode() {
    return id ^ name.hashCode() ^ address.hashCode() ^ ((int)salary);
    }
    Thanks you very much, i added this part in Employee.java Class and it works

    Java Code:
        @Override
       public boolean equals(Object obj){  
          
            if(!(obj instanceof Employee))  
                return false;  
              
            return (id == ((Employee) obj).getId());   
        }  
          
       
        @Override
        public int hashCode(){  
                
            return  id;    
        }
    But i have another question, how to make it compre not just up on one element suche id or name but more elements, such id and name and adrees for exsample, sow how to modify the equal method to do that

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,916
    Rep Power
    5

    Default Re: HashSet accept duplicated Value

    Well, forget the equals method for a second. If you have four int fields, a,b,c,d and want to see if they are equal to 1 thru 4 respectively and at the same time, how would you do it?

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default Re: HashSet accept duplicated Value

    the answer according how i understood your quistion is:

    Java Code:
    if ( a == 1 && b == 2 && c == 3 && d == 4)
    {
    //do something
    }

  9. #9
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default Re: HashSet accept duplicated Value

    ok for example i want to make compare as the following: if the ID or name is Duplicate in any object dann must not be added

    Java Code:
    @Override
       public boolean equals(Object obj1){  
     
            if(!(obj1 instanceof Employee))  
                return false;  
     
            return (id == ((Employee) obj1).getId() || name.equals(((Employee) obj1).getName()));   
        }  
     
     
        @Override
        public int hashCode(){  
     
            return  id ^ name.hashCode();    
        }
    but some how it don't work correctly

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,455
    Rep Power
    20

    Default Re: HashSet accept duplicated Value

    Hm, can't two employees (with different IDs) have the same name?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,261
    Rep Power
    6

    Default Re: HashSet accept duplicated Value

    Reminds me of an interesting article that pretty much made me feel stupid. I don't think it was this one but it is equally effective:

    Falsehoods Programmers Believe About Names | Kalzumeus Software

    EDIT: now that I think about it, it was someone on OTN that posted it. Might it have been you, Devilish Bartender?
    Last edited by gimbal2; 08-03-2013 at 12:21 PM.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,728
    Blog Entries
    7
    Rep Power
    21

    Default Re: HashSet accept duplicated Value

    Quote Originally Posted by vector_ever View Post
    ok for example i want to make compare as the following: if the ID or name is Duplicate in any object dann must not be added

    Java Code:
    @Override
       public boolean equals(Object obj1){  
     
            if(!(obj1 instanceof Employee))  
                return false;  
     
            return (id == ((Employee) obj1).getId() || name.equals(((Employee) obj1).getName()));   
        }  
     
     
        @Override
        public int hashCode(){  
     
            return  id ^ name.hashCode();    
        }
    but some how it don't work correctly
    The Jones's and Smith's and Doe's have it rough in your system ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  13. #13
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default Re: HashSet accept duplicated Value

    Hm, can't two employees (with different IDs) have the same name?
    It is not the issue, i talk about the principle (although i it possible the one employee have the same name and id but different address) any way it is doesn't matter

    waht i wanted to say, that how to make comparison according to multi attribute not just one

    The Jones's and Smith's and Doe's have it rough in your system
    what about that!!!

  14. #14
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,728
    Blog Entries
    7
    Rep Power
    21

    Default Re: HashSet accept duplicated Value

    First you did it correct in the example code but in your 'final' code you introduced the or (||) operator, so if the names are equal or the ID is equal you consider two Employees to be equal (but not in the hashCode() method); that doesn't make sense ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  15. #15
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default Re: HashSet accept duplicated Value

    First you did it correct in the example code but in your 'final' code you introduced the or (||) operator, so if the names are equal or the ID is equal you consider two Employees to be equal (but not in the hashCode() method); that doesn't make sense ...
    so assume here it not correct...
    Java Code:
    @Override
        public int hashCode(){  
      
            return  id ^ name.hashCode();    
        }
    so what the idea?

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,728
    Blog Entries
    7
    Rep Power
    21

    Default Re: HashSet accept duplicated Value

    You left out the equals( ... ) method (where the error was).

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,916
    Rep Power
    5

    Default Re: HashSet accept duplicated Value

    Read the hashCode contract here Object (Java Platform SE 7 ) - hashCode

    The main thing to remember is that if equals returns true then the hashCodes must be equal. If equals returns false the hashCodes may or may not be equal. In your example above, equals may return true because the names are equal. But the id's are different and the resulting hashCode would then be different. That violates the contract.

    Regards,
    Jim
    Last edited by jim829; 08-03-2013 at 06:57 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  18. #18
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default Re: HashSet accept duplicated Value

    Java Code:
    return (id == ((Employee) obj1).getId() || name.equals(((Employee) obj1).getName()));
    it will be return true if there any id "or" name, so it must not add it in the HashSet, so where the error?????

  19. #19
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,455
    Rep Power
    20

    Default Re: HashSet accept duplicated Value

    I mentioned the equals(...) / hashCode() contract at #2; Jim gave you a link in #17.

    Do you expect someone here to copy and paste the information here for you, or are you capable of clicking a link and reading it for yourself?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  20. #20
    vector_ever is offline Senior Member
    Join Date
    Jul 2013
    Posts
    187
    Rep Power
    2

    Default Re: HashSet accept duplicated Value

    I mentioned the equals(...) / hashCode() contract at #2; Jim gave you a link in #17
    so thank you and Jim and every one helped me

    Do you expect someone here to copy and paste the information here for you, or are you capable of clicking a link and reading it for yourself?
    i wrote the link and don't need to write such as comment, all what i want to refer to the problem is what i mean it in my last answer wrong ??

Page 1 of 2 12 LastLast

Similar Threads

  1. Need Help!Duplicated IO Class
    By oszc in forum New To Java
    Replies: 1
    Last Post: 11-05-2011, 08:40 AM
  2. data get duplicated on a Vector
    By khlitoshi in forum New To Java
    Replies: 15
    Last Post: 04-05-2011, 09:44 AM
  3. ArrayList duplicated/replaced objects
    By ImAFycus in forum New To Java
    Replies: 3
    Last Post: 05-29-2010, 08:58 PM
  4. Reset form button and duplicated data
    By dbashby in forum New To Java
    Replies: 7
    Last Post: 10-10-2009, 05:40 AM
  5. XML Parsing, strange empty/duplicated Nodes
    By Singing Boyo in forum Advanced Java
    Replies: 0
    Last Post: 08-18-2009, 07:57 AM

Posting Permissions

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