Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 21 of 21

Thread: HashSet store duplicated Value

  1. #1
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default HashSet store 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

    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
    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:
    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
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: HashSet store duplicated Value

    This thread has been cross posted here:

    http://www.java-forums.org/new-java/80569-hashset-accept-duplicated-value.html

    Although cross posting is allowed, for everyone's benefit, please read:

    Java Programming Forums Cross Posting Rules

    The Problems With Cross Posting


  3. #3
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: HashSet store duplicated Value

    i added this part in Employee.java Class and it works

        @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

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: HashSet store duplicated Value

    You will have to write the body of the method to compare each field individually and return the overall results

  5. #5
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: HashSet store duplicated Value

    i know that i must do so, but i don't know how

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: HashSet store duplicated Value

    How did you compare one field?
    Do the same thing on each field you want compared. Looks like the method already makes two comparisons, what is the problem in adding a third or fourth?
    Give it a try and see what you come up with or explain exactly what you are stuck on

  7. #7
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: HashSet store 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

        @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

  8. #8
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: HashSet store duplicated Value

    That would depend on how you define "correctly"

    || (or) returns true if either this or that are true.
    The desired result is probably to return true if this and that are both true

  9. #9
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: HashSet store duplicated Value

    return (id == ((Employee) obj1).getId() || name.equals(((Employee) obj1).getName()));

    means if, either id or name are duplicated in any object then don't add them in the HashSet

    On this basis, I wrote it.

    is that correct??

  10. #10
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: HashSet store duplicated Value

    I think that the use of the .equals method, in terms of comparing two objects, should return true if and only if all considered fields match in value
    It looks more like what you need here is to determine either the name or id are a match. Is this right?
    If so I suggest not using the .equals method, as it is normally used as described above in this post.

    Quote Originally Posted by vector_ever View Post
    if, either id or name are duplicated in any object then don't add them in the HashSet
    For clarity, "any object" here, realize this only checks the object receiving the message with the given object (obj1 in the sample), and not against a collection of objects (those in the hash set)

  11. #11
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: HashSet store duplicated Value

    and how you suggest to use equal() method to give me the desired result, what should i add in my equal and Hashcode methods?

  12. #12
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: HashSet store duplicated Value

    Hello.
    Even though in your fist posted code some objects have same values but their hashcodes are different.
    So for Set, these are distinct objects. If a same object is added several times then the set ignores duplicates.
    So you will have to tell the JVM when are two objects same. Either one field is same or all fields are same or some fields are same.
    Based on your requirement check for the equality of corresponding fields in the two objects.
    And return true/false appropriately.
    Also make sure you use AND and OR operators rightly.
    If you are still confused then just put your requirements for two objects to be same.
    Then we can help you write the condition.

    Syed.

  13. #13
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: HashSet store duplicated Value

    I put it
        @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();    
        }
    and again if, either id or name are duplicated in any object then don't add them in the HashSet

    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?????

  14. #14
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: HashSet store duplicated Value

    Hello.
    Just try this. It shall work.

    *code removed*

    Let me know if it is resolved. I don't think you need to override hashcode().
    Syed.
    Last edited by jps; August 3rd, 2013 at 03:15 PM. Reason: spoonfeeding

  15. #15
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: HashSet store duplicated Value

    @syedbhai
    We strive to help people in solving their problems, without providing solutions, and we thank you to do the same.
    Please read: The problem with spoonfeeding.

  16. The Following User Says Thank You to jps For This Useful Post:

    copeg (August 3rd, 2013)

  17. #16
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: HashSet store duplicated Value

    jps,
    I have already read your post "The Problem with Spoonfeeding" earlier.
    After that I am trying my best to avoid spoonfeeding.

    If you see my recent posts I am hardly providing any code these days. I am indeed just giving hints to the people to solve their problems.

    But for this guy I believed it is not spoonfeeding anymore.
    Because i thought he really tried a lot. He even posted his code.
    I did not provide any full solution from my side. I just helped him come up with correct if condition.
    Sometimes a person may try his best but may not be able to come up with the exact logic.
    Then how can we help him?

    Syed.

  18. #17
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: HashSet store duplicated Value

    Quote Originally Posted by syedbhai View Post
    Sometimes a person may try his best but may not be able to come up with the exact logic.
    Then how can we help him?
    Syed.
    Suggest search keywords
    Provide links to tutorials and/or documentation
    Explain functionality of incorrectly used keywords/symbols

    Much help can be provided without resorting to providing functional code. Ultimately the goal is not to be sure they get the code working, it is to get them to understand why it doesn't work so that they can start working on a solution of their own, to develop problem solving skills, not just to learn the syntax of a given language

  19. #18
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: HashSet store duplicated Value

    Now what the next, any advanced help??

  20. #19
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: HashSet store duplicated Value

    Looking over the code, I do not see where the equals method was overridden, nor do I see where it is being called. (yes I saw the snippet, but I do not see the method in the code in the OP)
    If you want to compare two fields of an object with the same two fields of a group of objects, you will have to do exactly that. Dumping them into a collection will not automatically sort out objects with a duplicated value in this or that field.
    Iterate the collection and make the comparisons you wish to make.

  21. #20
    Member
    Join Date
    Jul 2013
    Posts
    46
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: HashSet store duplicated Value

    I still always incapable to to improve it or understand your ideas

     return (id == ((Employee) obj1).getId() || name.equals(((Employee) obj1).getName()))
    I thought it is enough since whatever if any operand return true, the method will return true, but i know it is not the correct method because it is not working correctly

    Sorry but i can't bring any new i just tried and read tutorial and in Google

  22. #21
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: HashSet store duplicated Value

    Looking at the code in the first post, which seems to be the only "complete" collection of code, I do not see a call to the equals method, nor do I see the method. Post the version of the code you are currently working with, I fear I may be causing more confusion for you at this point.
    As a side note it looks like the method would return what you are expecting (among the two objects involved anyway), so I suspect there is a different issue

Similar Threads

  1. Problem with equality check with HashSet
    By jmegha in forum Member Introductions
    Replies: 2
    Last Post: June 15th, 2011, 07:28 AM
  2. Using Vector, data get duplicated
    By khlitoshi in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 4th, 2011, 12:02 PM
  3. error in HashSet
    By harsh23 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 4th, 2011, 09:18 AM
  4. detect duplicated programs
    By pulsarsitra in forum Java Theory & Questions
    Replies: 0
    Last Post: January 13th, 2011, 11:54 AM
  5. Removing objects from a hashSet
    By JohnTor in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 4th, 2010, 03:03 PM