Comparing objects in HashSet












0















I'm making a 2D game that has a stars in it. I decided to create constructor in class named Star that gives random coordinates.



public Star(){
super(0,0);
x = randomX.nextInt(maxX - minX + 1);
y = randomY.nextInt(maxX - minY + 1);
}


Then, in other class I put them in HashSet



Set<Star> star = new HashSet<>();

public Set<Star> generateStars(){
while (star.size() < numberOfStars){
star.add(new Star());
}
return star;
}


Of course, I have render and tick methods but I think it's not worth to paste them. My lecturer told me that there can be same stars and to prevent that I should use identity function using hashcodes. Can someone help me figure that out ? I imagine that this function should check if the hashcodes are the same and if it's the case it should return only one value that way we will add 1 object instead of 2 into the HashSet. Am I right ?










share|improve this question


















  • 1





    What do you mean by same stars? If the criteria for equality is same coordinates, just generate hashcode and equals depending on the coordinates. If not, just choose the appropriate criteria for equality and override hashcode and equals depending on it.

    – Nenad
    Nov 22 '18 at 22:05






  • 1





    Your constructor has some problems with it, it would probably be better to use the same RNG. Also your y coord is using the maxX variable.

    – van dench
    Nov 22 '18 at 22:07











  • Yes, same I mean coordinates.

    – Saulius Meidus
    Nov 22 '18 at 22:19











  • You need to create a hashCode and equals method. You can generate these using your IDE.

    – Peter Lawrey
    Nov 23 '18 at 7:23
















0















I'm making a 2D game that has a stars in it. I decided to create constructor in class named Star that gives random coordinates.



public Star(){
super(0,0);
x = randomX.nextInt(maxX - minX + 1);
y = randomY.nextInt(maxX - minY + 1);
}


Then, in other class I put them in HashSet



Set<Star> star = new HashSet<>();

public Set<Star> generateStars(){
while (star.size() < numberOfStars){
star.add(new Star());
}
return star;
}


Of course, I have render and tick methods but I think it's not worth to paste them. My lecturer told me that there can be same stars and to prevent that I should use identity function using hashcodes. Can someone help me figure that out ? I imagine that this function should check if the hashcodes are the same and if it's the case it should return only one value that way we will add 1 object instead of 2 into the HashSet. Am I right ?










share|improve this question


















  • 1





    What do you mean by same stars? If the criteria for equality is same coordinates, just generate hashcode and equals depending on the coordinates. If not, just choose the appropriate criteria for equality and override hashcode and equals depending on it.

    – Nenad
    Nov 22 '18 at 22:05






  • 1





    Your constructor has some problems with it, it would probably be better to use the same RNG. Also your y coord is using the maxX variable.

    – van dench
    Nov 22 '18 at 22:07











  • Yes, same I mean coordinates.

    – Saulius Meidus
    Nov 22 '18 at 22:19











  • You need to create a hashCode and equals method. You can generate these using your IDE.

    – Peter Lawrey
    Nov 23 '18 at 7:23














0












0








0








I'm making a 2D game that has a stars in it. I decided to create constructor in class named Star that gives random coordinates.



public Star(){
super(0,0);
x = randomX.nextInt(maxX - minX + 1);
y = randomY.nextInt(maxX - minY + 1);
}


Then, in other class I put them in HashSet



Set<Star> star = new HashSet<>();

public Set<Star> generateStars(){
while (star.size() < numberOfStars){
star.add(new Star());
}
return star;
}


Of course, I have render and tick methods but I think it's not worth to paste them. My lecturer told me that there can be same stars and to prevent that I should use identity function using hashcodes. Can someone help me figure that out ? I imagine that this function should check if the hashcodes are the same and if it's the case it should return only one value that way we will add 1 object instead of 2 into the HashSet. Am I right ?










share|improve this question














I'm making a 2D game that has a stars in it. I decided to create constructor in class named Star that gives random coordinates.



public Star(){
super(0,0);
x = randomX.nextInt(maxX - minX + 1);
y = randomY.nextInt(maxX - minY + 1);
}


Then, in other class I put them in HashSet



Set<Star> star = new HashSet<>();

public Set<Star> generateStars(){
while (star.size() < numberOfStars){
star.add(new Star());
}
return star;
}


Of course, I have render and tick methods but I think it's not worth to paste them. My lecturer told me that there can be same stars and to prevent that I should use identity function using hashcodes. Can someone help me figure that out ? I imagine that this function should check if the hashcodes are the same and if it's the case it should return only one value that way we will add 1 object instead of 2 into the HashSet. Am I right ?







java collections






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 21:53









Saulius MeidusSaulius Meidus

244




244








  • 1





    What do you mean by same stars? If the criteria for equality is same coordinates, just generate hashcode and equals depending on the coordinates. If not, just choose the appropriate criteria for equality and override hashcode and equals depending on it.

    – Nenad
    Nov 22 '18 at 22:05






  • 1





    Your constructor has some problems with it, it would probably be better to use the same RNG. Also your y coord is using the maxX variable.

    – van dench
    Nov 22 '18 at 22:07











  • Yes, same I mean coordinates.

    – Saulius Meidus
    Nov 22 '18 at 22:19











  • You need to create a hashCode and equals method. You can generate these using your IDE.

    – Peter Lawrey
    Nov 23 '18 at 7:23














  • 1





    What do you mean by same stars? If the criteria for equality is same coordinates, just generate hashcode and equals depending on the coordinates. If not, just choose the appropriate criteria for equality and override hashcode and equals depending on it.

    – Nenad
    Nov 22 '18 at 22:05






  • 1





    Your constructor has some problems with it, it would probably be better to use the same RNG. Also your y coord is using the maxX variable.

    – van dench
    Nov 22 '18 at 22:07











  • Yes, same I mean coordinates.

    – Saulius Meidus
    Nov 22 '18 at 22:19











  • You need to create a hashCode and equals method. You can generate these using your IDE.

    – Peter Lawrey
    Nov 23 '18 at 7:23








1




1





What do you mean by same stars? If the criteria for equality is same coordinates, just generate hashcode and equals depending on the coordinates. If not, just choose the appropriate criteria for equality and override hashcode and equals depending on it.

– Nenad
Nov 22 '18 at 22:05





What do you mean by same stars? If the criteria for equality is same coordinates, just generate hashcode and equals depending on the coordinates. If not, just choose the appropriate criteria for equality and override hashcode and equals depending on it.

– Nenad
Nov 22 '18 at 22:05




1




1





Your constructor has some problems with it, it would probably be better to use the same RNG. Also your y coord is using the maxX variable.

– van dench
Nov 22 '18 at 22:07





Your constructor has some problems with it, it would probably be better to use the same RNG. Also your y coord is using the maxX variable.

– van dench
Nov 22 '18 at 22:07













Yes, same I mean coordinates.

– Saulius Meidus
Nov 22 '18 at 22:19





Yes, same I mean coordinates.

– Saulius Meidus
Nov 22 '18 at 22:19













You need to create a hashCode and equals method. You can generate these using your IDE.

– Peter Lawrey
Nov 23 '18 at 7:23





You need to create a hashCode and equals method. You can generate these using your IDE.

– Peter Lawrey
Nov 23 '18 at 7:23












4 Answers
4






active

oldest

votes


















1














Overriding the hashCode() method alone in your Star class will not work you will have to override the equals() method.



See the following code where we don't override the equals() method:



class Star {
int x, y;

public Star(int x, int y) {
this.x = x;
this.y = y;
}

@Override
public int hashCode() {
return Objects.hash(x, y);
}
}

public class Main {
public static void main(String args) {
Star s1 = new Star(0, 0);
Star s3 = new Star(0, 0);
Star s2 = new Star(31, -31*31);
Set<Star> set = new HashSet<>();
set.add(s1);
set.add(s2);
System.out.println(set.size());
}
}


This will print 3 (instead of 2 what you might expect).



The reason for this is that the add method of java.util.Set compares 2 objects based on equals() method and not based on hashCode() method.



In the above code for the Star class, if you add the equals() method the output will be 2 now. For your reference the you can override the equals() method as follows:



@Override
public boolean equals(Object startObject) {
if (this == startObject) return true;
if (startObject == null || getClass() != startObject.getClass()) return false;
Star star = (Star) startObject;
return x == star.x &&
y == star.y;
}


So why do you need to add hashCode()?




  1. As you are using HashSet the add method behind the scene will call the equals() method and will also call hashCode() to decide the bucket in which the new object should be put. To maintain the contract of hashCode() and equals() Both should be overridden.

  2. When ever you override equals(), it is recommended to override hashCode() also. (Vice-versa is also true). See this link for details.


Contract for hashCode() and equals(): If for two objects say o1 and o2, o1.equals(o2) is true then hash of o1 and o2 should be same.



Make sure that you understand this properly, from the above statement it is not implied that if the hash of 2 objects are same, then o1.equals(o2) should return true. It can be possible that for 2 objects, their hash is same but the o1.equals(o2) returns false



See here, what Object's hashCode() method guarantees.



See this link to get more detailed information about this topic.






share|improve this answer































    2














    In java, when adding an object to a HashSet, the add method uses the 'equals' method, which is part of the Object class (however you can override it) in order to determine if the set already contains the object you are trying to add, see : https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html



    However, if you are overriding the equals method then you should also override the hashCode method, this is very well explained in the following post : Why do I need to override the equals and hashCode methods in Java?



    If you are going to follow this advice, I would also advise using ApacheCommonsLang EqualsBuilder and HashCodeBuilder if your lecturer allows it as they provide a solid implementation based on the rules laid out in the book 'Effective Java' by Joshua Bloch



    To override the equals method in your Star class, you want to think about the criteria that make two star objects equal. From your example this might be that both of them have the same x and y co-ordinates.






    share|improve this answer































      0














      you can override hashCode() method from Object. So, in your Star class, add:



      @Override
      public int hashCode() {
      in hash = .... //make your hash code about the coordinates of your star.
      return hash;
      }


      so, when you place a new star with the same co-ordiante in the hash map, it will overwrite the previous start with the same co-ordiantes if already present in the map.






      share|improve this answer































        0














        You have to implement hashCode and equals.
        the code should be like this:



          public static class Star {
        int x, y;
        public Star(int x, int y) {
        this.x = x;
        this.y = y;
        }

        @Override
        public int hashCode() {
        return x * 1000 + y;
        }

        @Override
        public boolean equals(Object obj) {
        if (obj instanceof Star) {
        Star s = (Star) obj;
        return this.x == s.x && this.y == s.y;
        }

        return false;
        }

        }

        public static void main(String args) throws Exception {
        HashSet<Star> set = new HashSet<Star>();
        set.add(new Star(1, 1));
        set.add(new Star(1, 1));

        System.out.println(set.size());
        }


        note: choose the suitable hashcode function for you. I assumed here that y should always be less than 1000.






        share|improve this answer


























        • It's ok to have conflicts within the hashset. do you gurantee that String.hashcode return different hashcodes for every possible strings in the world? that's why we need equals method!!

          – Mahmoud Hanafy
          Nov 22 '18 at 22:17











        • please suggest different implementation for the hashcode method?

          – Mahmoud Hanafy
          Nov 22 '18 at 22:18











        • I added a different implementation for hashcode, but I still don't guarantee that all possible objects will have different hashcodes.

          – Mahmoud Hanafy
          Nov 22 '18 at 22:23











        • Producing distinct hash results for unequal objects will improve the performance of hashed collections. You should aim to produce an unequal hash if the objects are unequal. This allows containers to uniformly distribute collections of unequal instances across all possible hash values. I suggest some hash of form: h(star) = m * star.x + star.y + c for some scalar m and offset c. The offset c is important for distinguishing the star (0,0) from null. The values used for the constants are arbitrary.

          – flakes
          Nov 22 '18 at 22:37













        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438370%2fcomparing-objects-in-hashset%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        Overriding the hashCode() method alone in your Star class will not work you will have to override the equals() method.



        See the following code where we don't override the equals() method:



        class Star {
        int x, y;

        public Star(int x, int y) {
        this.x = x;
        this.y = y;
        }

        @Override
        public int hashCode() {
        return Objects.hash(x, y);
        }
        }

        public class Main {
        public static void main(String args) {
        Star s1 = new Star(0, 0);
        Star s3 = new Star(0, 0);
        Star s2 = new Star(31, -31*31);
        Set<Star> set = new HashSet<>();
        set.add(s1);
        set.add(s2);
        System.out.println(set.size());
        }
        }


        This will print 3 (instead of 2 what you might expect).



        The reason for this is that the add method of java.util.Set compares 2 objects based on equals() method and not based on hashCode() method.



        In the above code for the Star class, if you add the equals() method the output will be 2 now. For your reference the you can override the equals() method as follows:



        @Override
        public boolean equals(Object startObject) {
        if (this == startObject) return true;
        if (startObject == null || getClass() != startObject.getClass()) return false;
        Star star = (Star) startObject;
        return x == star.x &&
        y == star.y;
        }


        So why do you need to add hashCode()?




        1. As you are using HashSet the add method behind the scene will call the equals() method and will also call hashCode() to decide the bucket in which the new object should be put. To maintain the contract of hashCode() and equals() Both should be overridden.

        2. When ever you override equals(), it is recommended to override hashCode() also. (Vice-versa is also true). See this link for details.


        Contract for hashCode() and equals(): If for two objects say o1 and o2, o1.equals(o2) is true then hash of o1 and o2 should be same.



        Make sure that you understand this properly, from the above statement it is not implied that if the hash of 2 objects are same, then o1.equals(o2) should return true. It can be possible that for 2 objects, their hash is same but the o1.equals(o2) returns false



        See here, what Object's hashCode() method guarantees.



        See this link to get more detailed information about this topic.






        share|improve this answer




























          1














          Overriding the hashCode() method alone in your Star class will not work you will have to override the equals() method.



          See the following code where we don't override the equals() method:



          class Star {
          int x, y;

          public Star(int x, int y) {
          this.x = x;
          this.y = y;
          }

          @Override
          public int hashCode() {
          return Objects.hash(x, y);
          }
          }

          public class Main {
          public static void main(String args) {
          Star s1 = new Star(0, 0);
          Star s3 = new Star(0, 0);
          Star s2 = new Star(31, -31*31);
          Set<Star> set = new HashSet<>();
          set.add(s1);
          set.add(s2);
          System.out.println(set.size());
          }
          }


          This will print 3 (instead of 2 what you might expect).



          The reason for this is that the add method of java.util.Set compares 2 objects based on equals() method and not based on hashCode() method.



          In the above code for the Star class, if you add the equals() method the output will be 2 now. For your reference the you can override the equals() method as follows:



          @Override
          public boolean equals(Object startObject) {
          if (this == startObject) return true;
          if (startObject == null || getClass() != startObject.getClass()) return false;
          Star star = (Star) startObject;
          return x == star.x &&
          y == star.y;
          }


          So why do you need to add hashCode()?




          1. As you are using HashSet the add method behind the scene will call the equals() method and will also call hashCode() to decide the bucket in which the new object should be put. To maintain the contract of hashCode() and equals() Both should be overridden.

          2. When ever you override equals(), it is recommended to override hashCode() also. (Vice-versa is also true). See this link for details.


          Contract for hashCode() and equals(): If for two objects say o1 and o2, o1.equals(o2) is true then hash of o1 and o2 should be same.



          Make sure that you understand this properly, from the above statement it is not implied that if the hash of 2 objects are same, then o1.equals(o2) should return true. It can be possible that for 2 objects, their hash is same but the o1.equals(o2) returns false



          See here, what Object's hashCode() method guarantees.



          See this link to get more detailed information about this topic.






          share|improve this answer


























            1












            1








            1







            Overriding the hashCode() method alone in your Star class will not work you will have to override the equals() method.



            See the following code where we don't override the equals() method:



            class Star {
            int x, y;

            public Star(int x, int y) {
            this.x = x;
            this.y = y;
            }

            @Override
            public int hashCode() {
            return Objects.hash(x, y);
            }
            }

            public class Main {
            public static void main(String args) {
            Star s1 = new Star(0, 0);
            Star s3 = new Star(0, 0);
            Star s2 = new Star(31, -31*31);
            Set<Star> set = new HashSet<>();
            set.add(s1);
            set.add(s2);
            System.out.println(set.size());
            }
            }


            This will print 3 (instead of 2 what you might expect).



            The reason for this is that the add method of java.util.Set compares 2 objects based on equals() method and not based on hashCode() method.



            In the above code for the Star class, if you add the equals() method the output will be 2 now. For your reference the you can override the equals() method as follows:



            @Override
            public boolean equals(Object startObject) {
            if (this == startObject) return true;
            if (startObject == null || getClass() != startObject.getClass()) return false;
            Star star = (Star) startObject;
            return x == star.x &&
            y == star.y;
            }


            So why do you need to add hashCode()?




            1. As you are using HashSet the add method behind the scene will call the equals() method and will also call hashCode() to decide the bucket in which the new object should be put. To maintain the contract of hashCode() and equals() Both should be overridden.

            2. When ever you override equals(), it is recommended to override hashCode() also. (Vice-versa is also true). See this link for details.


            Contract for hashCode() and equals(): If for two objects say o1 and o2, o1.equals(o2) is true then hash of o1 and o2 should be same.



            Make sure that you understand this properly, from the above statement it is not implied that if the hash of 2 objects are same, then o1.equals(o2) should return true. It can be possible that for 2 objects, their hash is same but the o1.equals(o2) returns false



            See here, what Object's hashCode() method guarantees.



            See this link to get more detailed information about this topic.






            share|improve this answer













            Overriding the hashCode() method alone in your Star class will not work you will have to override the equals() method.



            See the following code where we don't override the equals() method:



            class Star {
            int x, y;

            public Star(int x, int y) {
            this.x = x;
            this.y = y;
            }

            @Override
            public int hashCode() {
            return Objects.hash(x, y);
            }
            }

            public class Main {
            public static void main(String args) {
            Star s1 = new Star(0, 0);
            Star s3 = new Star(0, 0);
            Star s2 = new Star(31, -31*31);
            Set<Star> set = new HashSet<>();
            set.add(s1);
            set.add(s2);
            System.out.println(set.size());
            }
            }


            This will print 3 (instead of 2 what you might expect).



            The reason for this is that the add method of java.util.Set compares 2 objects based on equals() method and not based on hashCode() method.



            In the above code for the Star class, if you add the equals() method the output will be 2 now. For your reference the you can override the equals() method as follows:



            @Override
            public boolean equals(Object startObject) {
            if (this == startObject) return true;
            if (startObject == null || getClass() != startObject.getClass()) return false;
            Star star = (Star) startObject;
            return x == star.x &&
            y == star.y;
            }


            So why do you need to add hashCode()?




            1. As you are using HashSet the add method behind the scene will call the equals() method and will also call hashCode() to decide the bucket in which the new object should be put. To maintain the contract of hashCode() and equals() Both should be overridden.

            2. When ever you override equals(), it is recommended to override hashCode() also. (Vice-versa is also true). See this link for details.


            Contract for hashCode() and equals(): If for two objects say o1 and o2, o1.equals(o2) is true then hash of o1 and o2 should be same.



            Make sure that you understand this properly, from the above statement it is not implied that if the hash of 2 objects are same, then o1.equals(o2) should return true. It can be possible that for 2 objects, their hash is same but the o1.equals(o2) returns false



            See here, what Object's hashCode() method guarantees.



            See this link to get more detailed information about this topic.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 22 '18 at 23:01









            Lavish KothariLavish Kothari

            728614




            728614

























                2














                In java, when adding an object to a HashSet, the add method uses the 'equals' method, which is part of the Object class (however you can override it) in order to determine if the set already contains the object you are trying to add, see : https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html



                However, if you are overriding the equals method then you should also override the hashCode method, this is very well explained in the following post : Why do I need to override the equals and hashCode methods in Java?



                If you are going to follow this advice, I would also advise using ApacheCommonsLang EqualsBuilder and HashCodeBuilder if your lecturer allows it as they provide a solid implementation based on the rules laid out in the book 'Effective Java' by Joshua Bloch



                To override the equals method in your Star class, you want to think about the criteria that make two star objects equal. From your example this might be that both of them have the same x and y co-ordinates.






                share|improve this answer




























                  2














                  In java, when adding an object to a HashSet, the add method uses the 'equals' method, which is part of the Object class (however you can override it) in order to determine if the set already contains the object you are trying to add, see : https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html



                  However, if you are overriding the equals method then you should also override the hashCode method, this is very well explained in the following post : Why do I need to override the equals and hashCode methods in Java?



                  If you are going to follow this advice, I would also advise using ApacheCommonsLang EqualsBuilder and HashCodeBuilder if your lecturer allows it as they provide a solid implementation based on the rules laid out in the book 'Effective Java' by Joshua Bloch



                  To override the equals method in your Star class, you want to think about the criteria that make two star objects equal. From your example this might be that both of them have the same x and y co-ordinates.






                  share|improve this answer


























                    2












                    2








                    2







                    In java, when adding an object to a HashSet, the add method uses the 'equals' method, which is part of the Object class (however you can override it) in order to determine if the set already contains the object you are trying to add, see : https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html



                    However, if you are overriding the equals method then you should also override the hashCode method, this is very well explained in the following post : Why do I need to override the equals and hashCode methods in Java?



                    If you are going to follow this advice, I would also advise using ApacheCommonsLang EqualsBuilder and HashCodeBuilder if your lecturer allows it as they provide a solid implementation based on the rules laid out in the book 'Effective Java' by Joshua Bloch



                    To override the equals method in your Star class, you want to think about the criteria that make two star objects equal. From your example this might be that both of them have the same x and y co-ordinates.






                    share|improve this answer













                    In java, when adding an object to a HashSet, the add method uses the 'equals' method, which is part of the Object class (however you can override it) in order to determine if the set already contains the object you are trying to add, see : https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html



                    However, if you are overriding the equals method then you should also override the hashCode method, this is very well explained in the following post : Why do I need to override the equals and hashCode methods in Java?



                    If you are going to follow this advice, I would also advise using ApacheCommonsLang EqualsBuilder and HashCodeBuilder if your lecturer allows it as they provide a solid implementation based on the rules laid out in the book 'Effective Java' by Joshua Bloch



                    To override the equals method in your Star class, you want to think about the criteria that make two star objects equal. From your example this might be that both of them have the same x and y co-ordinates.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 22 '18 at 22:17









                    Adam McClenaghanAdam McClenaghan

                    6614




                    6614























                        0














                        you can override hashCode() method from Object. So, in your Star class, add:



                        @Override
                        public int hashCode() {
                        in hash = .... //make your hash code about the coordinates of your star.
                        return hash;
                        }


                        so, when you place a new star with the same co-ordiante in the hash map, it will overwrite the previous start with the same co-ordiantes if already present in the map.






                        share|improve this answer




























                          0














                          you can override hashCode() method from Object. So, in your Star class, add:



                          @Override
                          public int hashCode() {
                          in hash = .... //make your hash code about the coordinates of your star.
                          return hash;
                          }


                          so, when you place a new star with the same co-ordiante in the hash map, it will overwrite the previous start with the same co-ordiantes if already present in the map.






                          share|improve this answer


























                            0












                            0








                            0







                            you can override hashCode() method from Object. So, in your Star class, add:



                            @Override
                            public int hashCode() {
                            in hash = .... //make your hash code about the coordinates of your star.
                            return hash;
                            }


                            so, when you place a new star with the same co-ordiante in the hash map, it will overwrite the previous start with the same co-ordiantes if already present in the map.






                            share|improve this answer













                            you can override hashCode() method from Object. So, in your Star class, add:



                            @Override
                            public int hashCode() {
                            in hash = .... //make your hash code about the coordinates of your star.
                            return hash;
                            }


                            so, when you place a new star with the same co-ordiante in the hash map, it will overwrite the previous start with the same co-ordiantes if already present in the map.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 22 '18 at 22:00









                            AppleCiderGuyAppleCiderGuy

                            618311




                            618311























                                0














                                You have to implement hashCode and equals.
                                the code should be like this:



                                  public static class Star {
                                int x, y;
                                public Star(int x, int y) {
                                this.x = x;
                                this.y = y;
                                }

                                @Override
                                public int hashCode() {
                                return x * 1000 + y;
                                }

                                @Override
                                public boolean equals(Object obj) {
                                if (obj instanceof Star) {
                                Star s = (Star) obj;
                                return this.x == s.x && this.y == s.y;
                                }

                                return false;
                                }

                                }

                                public static void main(String args) throws Exception {
                                HashSet<Star> set = new HashSet<Star>();
                                set.add(new Star(1, 1));
                                set.add(new Star(1, 1));

                                System.out.println(set.size());
                                }


                                note: choose the suitable hashcode function for you. I assumed here that y should always be less than 1000.






                                share|improve this answer


























                                • It's ok to have conflicts within the hashset. do you gurantee that String.hashcode return different hashcodes for every possible strings in the world? that's why we need equals method!!

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:17











                                • please suggest different implementation for the hashcode method?

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:18











                                • I added a different implementation for hashcode, but I still don't guarantee that all possible objects will have different hashcodes.

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:23











                                • Producing distinct hash results for unequal objects will improve the performance of hashed collections. You should aim to produce an unequal hash if the objects are unequal. This allows containers to uniformly distribute collections of unequal instances across all possible hash values. I suggest some hash of form: h(star) = m * star.x + star.y + c for some scalar m and offset c. The offset c is important for distinguishing the star (0,0) from null. The values used for the constants are arbitrary.

                                  – flakes
                                  Nov 22 '18 at 22:37


















                                0














                                You have to implement hashCode and equals.
                                the code should be like this:



                                  public static class Star {
                                int x, y;
                                public Star(int x, int y) {
                                this.x = x;
                                this.y = y;
                                }

                                @Override
                                public int hashCode() {
                                return x * 1000 + y;
                                }

                                @Override
                                public boolean equals(Object obj) {
                                if (obj instanceof Star) {
                                Star s = (Star) obj;
                                return this.x == s.x && this.y == s.y;
                                }

                                return false;
                                }

                                }

                                public static void main(String args) throws Exception {
                                HashSet<Star> set = new HashSet<Star>();
                                set.add(new Star(1, 1));
                                set.add(new Star(1, 1));

                                System.out.println(set.size());
                                }


                                note: choose the suitable hashcode function for you. I assumed here that y should always be less than 1000.






                                share|improve this answer


























                                • It's ok to have conflicts within the hashset. do you gurantee that String.hashcode return different hashcodes for every possible strings in the world? that's why we need equals method!!

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:17











                                • please suggest different implementation for the hashcode method?

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:18











                                • I added a different implementation for hashcode, but I still don't guarantee that all possible objects will have different hashcodes.

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:23











                                • Producing distinct hash results for unequal objects will improve the performance of hashed collections. You should aim to produce an unequal hash if the objects are unequal. This allows containers to uniformly distribute collections of unequal instances across all possible hash values. I suggest some hash of form: h(star) = m * star.x + star.y + c for some scalar m and offset c. The offset c is important for distinguishing the star (0,0) from null. The values used for the constants are arbitrary.

                                  – flakes
                                  Nov 22 '18 at 22:37
















                                0












                                0








                                0







                                You have to implement hashCode and equals.
                                the code should be like this:



                                  public static class Star {
                                int x, y;
                                public Star(int x, int y) {
                                this.x = x;
                                this.y = y;
                                }

                                @Override
                                public int hashCode() {
                                return x * 1000 + y;
                                }

                                @Override
                                public boolean equals(Object obj) {
                                if (obj instanceof Star) {
                                Star s = (Star) obj;
                                return this.x == s.x && this.y == s.y;
                                }

                                return false;
                                }

                                }

                                public static void main(String args) throws Exception {
                                HashSet<Star> set = new HashSet<Star>();
                                set.add(new Star(1, 1));
                                set.add(new Star(1, 1));

                                System.out.println(set.size());
                                }


                                note: choose the suitable hashcode function for you. I assumed here that y should always be less than 1000.






                                share|improve this answer















                                You have to implement hashCode and equals.
                                the code should be like this:



                                  public static class Star {
                                int x, y;
                                public Star(int x, int y) {
                                this.x = x;
                                this.y = y;
                                }

                                @Override
                                public int hashCode() {
                                return x * 1000 + y;
                                }

                                @Override
                                public boolean equals(Object obj) {
                                if (obj instanceof Star) {
                                Star s = (Star) obj;
                                return this.x == s.x && this.y == s.y;
                                }

                                return false;
                                }

                                }

                                public static void main(String args) throws Exception {
                                HashSet<Star> set = new HashSet<Star>();
                                set.add(new Star(1, 1));
                                set.add(new Star(1, 1));

                                System.out.println(set.size());
                                }


                                note: choose the suitable hashcode function for you. I assumed here that y should always be less than 1000.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 23 '18 at 14:43

























                                answered Nov 22 '18 at 22:10









                                Mahmoud HanafyMahmoud Hanafy

                                96511528




                                96511528













                                • It's ok to have conflicts within the hashset. do you gurantee that String.hashcode return different hashcodes for every possible strings in the world? that's why we need equals method!!

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:17











                                • please suggest different implementation for the hashcode method?

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:18











                                • I added a different implementation for hashcode, but I still don't guarantee that all possible objects will have different hashcodes.

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:23











                                • Producing distinct hash results for unequal objects will improve the performance of hashed collections. You should aim to produce an unequal hash if the objects are unequal. This allows containers to uniformly distribute collections of unequal instances across all possible hash values. I suggest some hash of form: h(star) = m * star.x + star.y + c for some scalar m and offset c. The offset c is important for distinguishing the star (0,0) from null. The values used for the constants are arbitrary.

                                  – flakes
                                  Nov 22 '18 at 22:37





















                                • It's ok to have conflicts within the hashset. do you gurantee that String.hashcode return different hashcodes for every possible strings in the world? that's why we need equals method!!

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:17











                                • please suggest different implementation for the hashcode method?

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:18











                                • I added a different implementation for hashcode, but I still don't guarantee that all possible objects will have different hashcodes.

                                  – Mahmoud Hanafy
                                  Nov 22 '18 at 22:23











                                • Producing distinct hash results for unequal objects will improve the performance of hashed collections. You should aim to produce an unequal hash if the objects are unequal. This allows containers to uniformly distribute collections of unequal instances across all possible hash values. I suggest some hash of form: h(star) = m * star.x + star.y + c for some scalar m and offset c. The offset c is important for distinguishing the star (0,0) from null. The values used for the constants are arbitrary.

                                  – flakes
                                  Nov 22 '18 at 22:37



















                                It's ok to have conflicts within the hashset. do you gurantee that String.hashcode return different hashcodes for every possible strings in the world? that's why we need equals method!!

                                – Mahmoud Hanafy
                                Nov 22 '18 at 22:17





                                It's ok to have conflicts within the hashset. do you gurantee that String.hashcode return different hashcodes for every possible strings in the world? that's why we need equals method!!

                                – Mahmoud Hanafy
                                Nov 22 '18 at 22:17













                                please suggest different implementation for the hashcode method?

                                – Mahmoud Hanafy
                                Nov 22 '18 at 22:18





                                please suggest different implementation for the hashcode method?

                                – Mahmoud Hanafy
                                Nov 22 '18 at 22:18













                                I added a different implementation for hashcode, but I still don't guarantee that all possible objects will have different hashcodes.

                                – Mahmoud Hanafy
                                Nov 22 '18 at 22:23





                                I added a different implementation for hashcode, but I still don't guarantee that all possible objects will have different hashcodes.

                                – Mahmoud Hanafy
                                Nov 22 '18 at 22:23













                                Producing distinct hash results for unequal objects will improve the performance of hashed collections. You should aim to produce an unequal hash if the objects are unequal. This allows containers to uniformly distribute collections of unequal instances across all possible hash values. I suggest some hash of form: h(star) = m * star.x + star.y + c for some scalar m and offset c. The offset c is important for distinguishing the star (0,0) from null. The values used for the constants are arbitrary.

                                – flakes
                                Nov 22 '18 at 22:37







                                Producing distinct hash results for unequal objects will improve the performance of hashed collections. You should aim to produce an unequal hash if the objects are unequal. This allows containers to uniformly distribute collections of unequal instances across all possible hash values. I suggest some hash of form: h(star) = m * star.x + star.y + c for some scalar m and offset c. The offset c is important for distinguishing the star (0,0) from null. The values used for the constants are arbitrary.

                                – flakes
                                Nov 22 '18 at 22:37




















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438370%2fcomparing-objects-in-hashset%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Tonle Sap (See)

                                I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                                Guatemaltekische Davis-Cup-Mannschaft