How to compare objects contained in the set? What would be a good hashcode and equals implementation here?












1















import java.util.*;

public class Tester
{
public static void main(String args)
{
Set<Point> set = new HashSet<Point>();
Point A = new Point(0, 0);
set.add(A);
Point B = new Point(0, 0);
System.out.println(set.contains(B));
}
}

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

public boolean equals(Object o)
{
// Not sure/
}

public int hashcode()
{
// Not sure?
}
}


I'm using a Point object to represent every cell of a 2d matrix. For DFS, I need to mark nodes as visited. However, the code returns false although it has object with value (0, 0). I think this probably requires a hashcode and equals implementation since by default the equals() looks for object reference.



So my question is, what would be a good hashcode and equals implementation here?
1. No constraints on the x and y.
2. x and y at most would be 1000.










share|improve this question




















  • 1





    Why not just use the auto-generated methods given by the IDE?

    – Nicholas K
    Jan 1 at 7:14











  • @NicholasK this is more like a leetcode exercise

    – user2609410
    Jan 1 at 7:23
















1















import java.util.*;

public class Tester
{
public static void main(String args)
{
Set<Point> set = new HashSet<Point>();
Point A = new Point(0, 0);
set.add(A);
Point B = new Point(0, 0);
System.out.println(set.contains(B));
}
}

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

public boolean equals(Object o)
{
// Not sure/
}

public int hashcode()
{
// Not sure?
}
}


I'm using a Point object to represent every cell of a 2d matrix. For DFS, I need to mark nodes as visited. However, the code returns false although it has object with value (0, 0). I think this probably requires a hashcode and equals implementation since by default the equals() looks for object reference.



So my question is, what would be a good hashcode and equals implementation here?
1. No constraints on the x and y.
2. x and y at most would be 1000.










share|improve this question




















  • 1





    Why not just use the auto-generated methods given by the IDE?

    – Nicholas K
    Jan 1 at 7:14











  • @NicholasK this is more like a leetcode exercise

    – user2609410
    Jan 1 at 7:23














1












1








1








import java.util.*;

public class Tester
{
public static void main(String args)
{
Set<Point> set = new HashSet<Point>();
Point A = new Point(0, 0);
set.add(A);
Point B = new Point(0, 0);
System.out.println(set.contains(B));
}
}

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

public boolean equals(Object o)
{
// Not sure/
}

public int hashcode()
{
// Not sure?
}
}


I'm using a Point object to represent every cell of a 2d matrix. For DFS, I need to mark nodes as visited. However, the code returns false although it has object with value (0, 0). I think this probably requires a hashcode and equals implementation since by default the equals() looks for object reference.



So my question is, what would be a good hashcode and equals implementation here?
1. No constraints on the x and y.
2. x and y at most would be 1000.










share|improve this question
















import java.util.*;

public class Tester
{
public static void main(String args)
{
Set<Point> set = new HashSet<Point>();
Point A = new Point(0, 0);
set.add(A);
Point B = new Point(0, 0);
System.out.println(set.contains(B));
}
}

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

public boolean equals(Object o)
{
// Not sure/
}

public int hashcode()
{
// Not sure?
}
}


I'm using a Point object to represent every cell of a 2d matrix. For DFS, I need to mark nodes as visited. However, the code returns false although it has object with value (0, 0). I think this probably requires a hashcode and equals implementation since by default the equals() looks for object reference.



So my question is, what would be a good hashcode and equals implementation here?
1. No constraints on the x and y.
2. x and y at most would be 1000.







java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 1 at 7:21









John Kugelman

243k54406457




243k54406457










asked Jan 1 at 7:05









user2609410user2609410

6910




6910








  • 1





    Why not just use the auto-generated methods given by the IDE?

    – Nicholas K
    Jan 1 at 7:14











  • @NicholasK this is more like a leetcode exercise

    – user2609410
    Jan 1 at 7:23














  • 1





    Why not just use the auto-generated methods given by the IDE?

    – Nicholas K
    Jan 1 at 7:14











  • @NicholasK this is more like a leetcode exercise

    – user2609410
    Jan 1 at 7:23








1




1





Why not just use the auto-generated methods given by the IDE?

– Nicholas K
Jan 1 at 7:14





Why not just use the auto-generated methods given by the IDE?

– Nicholas K
Jan 1 at 7:14













@NicholasK this is more like a leetcode exercise

– user2609410
Jan 1 at 7:23





@NicholasK this is more like a leetcode exercise

– user2609410
Jan 1 at 7:23












2 Answers
2






active

oldest

votes


















2














Your equals method should return true if and only if both objects are intances of Point and both have the same x and y values:



@Override
public boolean equals(Object o)
{
if (o == this)
return true;
if (!(o instanceof Point))
return false;
Point other = (Point) o;
return this.x == other.x && this.y == other.y;
}


For hashCode, you can use a helper method:



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


EDIT: using the @Override annotation is optional, but it will save you from typos such as hashcode instead of hashCode.






share|improve this answer


























  • Can you explain what purpose does this solve? return Objects.hash(x,y); And how it works internally?

    – user2609410
    Jan 1 at 7:13











  • And I tried it out, still shows false. @Eran (updated the code in my description) still fails

    – user2609410
    Jan 1 at 7:17








  • 1





    @user2609410 it returns a function of x and y, so if point1.equals(point2)==true, point1.hashCode()==point2.hashCode() will also be true. The actual implementation is 31 * (31 + x) + y

    – Eran
    Jan 1 at 7:18











  • @user2609410 that's because you had a typo - it should be hashCode, not hashcode

    – Eran
    Jan 1 at 7:21











  • Thanks! Ill update the desc and mark your answer as solution

    – user2609410
    Jan 1 at 7:21





















1














You used HashSet for Set implementation which uses hashing to store elements. hashcode() and equals() are used for hashing and comparing elements. There are some guidelines to override hashcode() and equals() method.



The general contract of hashCode is:




  1. hashcode method should consistent. That is it should return same integer on mulitple call on same object.

  2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  3. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.


Guideline for equals method.




  1. It is reflexive: for any non-null reference value x, x.equals(x) should return true.

  2. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

  3. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

  4. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.

  5. For any non-null reference value x, x.equals(null) should return false.


Source:-Hashcode Javadoc, Equals javadoc






share|improve this answer























    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%2f53993657%2fhow-to-compare-objects-contained-in-the-set-what-would-be-a-good-hashcode-and-e%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Your equals method should return true if and only if both objects are intances of Point and both have the same x and y values:



    @Override
    public boolean equals(Object o)
    {
    if (o == this)
    return true;
    if (!(o instanceof Point))
    return false;
    Point other = (Point) o;
    return this.x == other.x && this.y == other.y;
    }


    For hashCode, you can use a helper method:



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


    EDIT: using the @Override annotation is optional, but it will save you from typos such as hashcode instead of hashCode.






    share|improve this answer


























    • Can you explain what purpose does this solve? return Objects.hash(x,y); And how it works internally?

      – user2609410
      Jan 1 at 7:13











    • And I tried it out, still shows false. @Eran (updated the code in my description) still fails

      – user2609410
      Jan 1 at 7:17








    • 1





      @user2609410 it returns a function of x and y, so if point1.equals(point2)==true, point1.hashCode()==point2.hashCode() will also be true. The actual implementation is 31 * (31 + x) + y

      – Eran
      Jan 1 at 7:18











    • @user2609410 that's because you had a typo - it should be hashCode, not hashcode

      – Eran
      Jan 1 at 7:21











    • Thanks! Ill update the desc and mark your answer as solution

      – user2609410
      Jan 1 at 7:21


















    2














    Your equals method should return true if and only if both objects are intances of Point and both have the same x and y values:



    @Override
    public boolean equals(Object o)
    {
    if (o == this)
    return true;
    if (!(o instanceof Point))
    return false;
    Point other = (Point) o;
    return this.x == other.x && this.y == other.y;
    }


    For hashCode, you can use a helper method:



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


    EDIT: using the @Override annotation is optional, but it will save you from typos such as hashcode instead of hashCode.






    share|improve this answer


























    • Can you explain what purpose does this solve? return Objects.hash(x,y); And how it works internally?

      – user2609410
      Jan 1 at 7:13











    • And I tried it out, still shows false. @Eran (updated the code in my description) still fails

      – user2609410
      Jan 1 at 7:17








    • 1





      @user2609410 it returns a function of x and y, so if point1.equals(point2)==true, point1.hashCode()==point2.hashCode() will also be true. The actual implementation is 31 * (31 + x) + y

      – Eran
      Jan 1 at 7:18











    • @user2609410 that's because you had a typo - it should be hashCode, not hashcode

      – Eran
      Jan 1 at 7:21











    • Thanks! Ill update the desc and mark your answer as solution

      – user2609410
      Jan 1 at 7:21
















    2












    2








    2







    Your equals method should return true if and only if both objects are intances of Point and both have the same x and y values:



    @Override
    public boolean equals(Object o)
    {
    if (o == this)
    return true;
    if (!(o instanceof Point))
    return false;
    Point other = (Point) o;
    return this.x == other.x && this.y == other.y;
    }


    For hashCode, you can use a helper method:



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


    EDIT: using the @Override annotation is optional, but it will save you from typos such as hashcode instead of hashCode.






    share|improve this answer















    Your equals method should return true if and only if both objects are intances of Point and both have the same x and y values:



    @Override
    public boolean equals(Object o)
    {
    if (o == this)
    return true;
    if (!(o instanceof Point))
    return false;
    Point other = (Point) o;
    return this.x == other.x && this.y == other.y;
    }


    For hashCode, you can use a helper method:



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


    EDIT: using the @Override annotation is optional, but it will save you from typos such as hashcode instead of hashCode.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 1 at 7:23

























    answered Jan 1 at 7:10









    EranEran

    286k37464553




    286k37464553













    • Can you explain what purpose does this solve? return Objects.hash(x,y); And how it works internally?

      – user2609410
      Jan 1 at 7:13











    • And I tried it out, still shows false. @Eran (updated the code in my description) still fails

      – user2609410
      Jan 1 at 7:17








    • 1





      @user2609410 it returns a function of x and y, so if point1.equals(point2)==true, point1.hashCode()==point2.hashCode() will also be true. The actual implementation is 31 * (31 + x) + y

      – Eran
      Jan 1 at 7:18











    • @user2609410 that's because you had a typo - it should be hashCode, not hashcode

      – Eran
      Jan 1 at 7:21











    • Thanks! Ill update the desc and mark your answer as solution

      – user2609410
      Jan 1 at 7:21





















    • Can you explain what purpose does this solve? return Objects.hash(x,y); And how it works internally?

      – user2609410
      Jan 1 at 7:13











    • And I tried it out, still shows false. @Eran (updated the code in my description) still fails

      – user2609410
      Jan 1 at 7:17








    • 1





      @user2609410 it returns a function of x and y, so if point1.equals(point2)==true, point1.hashCode()==point2.hashCode() will also be true. The actual implementation is 31 * (31 + x) + y

      – Eran
      Jan 1 at 7:18











    • @user2609410 that's because you had a typo - it should be hashCode, not hashcode

      – Eran
      Jan 1 at 7:21











    • Thanks! Ill update the desc and mark your answer as solution

      – user2609410
      Jan 1 at 7:21



















    Can you explain what purpose does this solve? return Objects.hash(x,y); And how it works internally?

    – user2609410
    Jan 1 at 7:13





    Can you explain what purpose does this solve? return Objects.hash(x,y); And how it works internally?

    – user2609410
    Jan 1 at 7:13













    And I tried it out, still shows false. @Eran (updated the code in my description) still fails

    – user2609410
    Jan 1 at 7:17







    And I tried it out, still shows false. @Eran (updated the code in my description) still fails

    – user2609410
    Jan 1 at 7:17






    1




    1





    @user2609410 it returns a function of x and y, so if point1.equals(point2)==true, point1.hashCode()==point2.hashCode() will also be true. The actual implementation is 31 * (31 + x) + y

    – Eran
    Jan 1 at 7:18





    @user2609410 it returns a function of x and y, so if point1.equals(point2)==true, point1.hashCode()==point2.hashCode() will also be true. The actual implementation is 31 * (31 + x) + y

    – Eran
    Jan 1 at 7:18













    @user2609410 that's because you had a typo - it should be hashCode, not hashcode

    – Eran
    Jan 1 at 7:21





    @user2609410 that's because you had a typo - it should be hashCode, not hashcode

    – Eran
    Jan 1 at 7:21













    Thanks! Ill update the desc and mark your answer as solution

    – user2609410
    Jan 1 at 7:21







    Thanks! Ill update the desc and mark your answer as solution

    – user2609410
    Jan 1 at 7:21















    1














    You used HashSet for Set implementation which uses hashing to store elements. hashcode() and equals() are used for hashing and comparing elements. There are some guidelines to override hashcode() and equals() method.



    The general contract of hashCode is:




    1. hashcode method should consistent. That is it should return same integer on mulitple call on same object.

    2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

    3. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.


    Guideline for equals method.




    1. It is reflexive: for any non-null reference value x, x.equals(x) should return true.

    2. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

    3. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

    4. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.

    5. For any non-null reference value x, x.equals(null) should return false.


    Source:-Hashcode Javadoc, Equals javadoc






    share|improve this answer




























      1














      You used HashSet for Set implementation which uses hashing to store elements. hashcode() and equals() are used for hashing and comparing elements. There are some guidelines to override hashcode() and equals() method.



      The general contract of hashCode is:




      1. hashcode method should consistent. That is it should return same integer on mulitple call on same object.

      2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

      3. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.


      Guideline for equals method.




      1. It is reflexive: for any non-null reference value x, x.equals(x) should return true.

      2. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

      3. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

      4. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.

      5. For any non-null reference value x, x.equals(null) should return false.


      Source:-Hashcode Javadoc, Equals javadoc






      share|improve this answer


























        1












        1








        1







        You used HashSet for Set implementation which uses hashing to store elements. hashcode() and equals() are used for hashing and comparing elements. There are some guidelines to override hashcode() and equals() method.



        The general contract of hashCode is:




        1. hashcode method should consistent. That is it should return same integer on mulitple call on same object.

        2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

        3. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.


        Guideline for equals method.




        1. It is reflexive: for any non-null reference value x, x.equals(x) should return true.

        2. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

        3. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

        4. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.

        5. For any non-null reference value x, x.equals(null) should return false.


        Source:-Hashcode Javadoc, Equals javadoc






        share|improve this answer













        You used HashSet for Set implementation which uses hashing to store elements. hashcode() and equals() are used for hashing and comparing elements. There are some guidelines to override hashcode() and equals() method.



        The general contract of hashCode is:




        1. hashcode method should consistent. That is it should return same integer on mulitple call on same object.

        2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

        3. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.


        Guideline for equals method.




        1. It is reflexive: for any non-null reference value x, x.equals(x) should return true.

        2. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

        3. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

        4. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.

        5. For any non-null reference value x, x.equals(null) should return false.


        Source:-Hashcode Javadoc, Equals javadoc







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 1 at 7:28









        TarunTarun

        673414




        673414






























            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%2f53993657%2fhow-to-compare-objects-contained-in-the-set-what-would-be-a-good-hashcode-and-e%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

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas