a little bit confuse about HASH CODE

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    a little bit confuse about HASH CODE

    this is my code .....

    Code:
    class Object1
    {
      private int data;
      public Object1(int d)
      {
        data = d;
      }
      public int hashCode()
      {
        return 0;
      }
    }
    
    class HashCodeTest
    {
      public static void main(String args[])
      {
        Object1 o1 = new Object1(100);
        Object1 o2 = new Object1(200);
        System.out.println("The hash code for o1: " + o1.hashCode());
        System.out.println("The hash code for o2: " + o2.hashCode());
        System.out.println("o1=o2: " + o1.equals(o2));
      } 
    }
    on which basic the EQUALS method is implemented???

    as my two objects the hash code is same ....but the EQUALS method returns false.

    plz explain.

    regards.
    Last edited by JosAH; Apr 23 '07, 09:45 AM. Reason: changed the [quote] to [code]
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by dmjpro
    this is my code .....

    Code:
    class Object1
    {
      private int data;
      public Object1(int d)
      {
        data = d;
      }
      public int hashCode()
      {
        return 0;
      }
    }
    
    class HashCodeTest
    {
      public static void main(String args[])
      {
        Object1 o1 = new Object1(100);
        Object1 o2 = new Object1(200);
        System.out.println("The hash code for o1: " + o1.hashCode());
        System.out.println("The hash code for o2: " + o2.hashCode());
        System.out.println("o1=o2: " + o1.equals(o2));
      } 
    }
    on which basic the EQUALS method is implemented???

    as my two objects the hash code is same ....but the EQUALS method returns false.

    plz explain.

    regards.
    You didn't override the equals() method so the Object.equals() method is used
    here. Object.equals() uses reference equality, i.e. every two distinct instances
    of objects are considered not equal. This implies that only this will result as true:
    Code:
    Object o= new Object();
    System.out.println(o.equals(o));
    If objects are considered equal, then the hashCodes should be equal. The other
    way around isn't true, e.g. if the hashCodes are equal for two objects then the
    objects needn't be equal and if the hashCodes aren't equal then the two objects
    certainly aren't equal.

    The default implementations of equals() and hashCode() in class Object obey
    to this rule. If you overrride them both the new versions should also obey to this
    rule.

    kind regards,

    Jos

    Comment

    • dmjpro
      Top Contributor
      • Jan 2007
      • 2476

      #3
      thanx for ur reply.

      ok i see.

      Comment

      Working...