Hashcode and equals

后端 未结 7 2424
死守一世寂寞
死守一世寂寞 2020-11-30 14:00

equals and hashCode method must be consistent, which means that when two objects are equal according to equals method their hash

7条回答
  •  既然无缘
    2020-11-30 14:34

    HashValue and Hashvalue are two different identifiers

    if(oo instanceof HashValue) works because your class-name is HashValue not Hashvalue

    EDIT :

    Your code doesn't work because hh isn't in scope when you are using it.

    This works:

    /* A program to check hashcode values for object
    @Author Myth17
     */
    
    class HashValue 
    {
    
       int x;
    
       public boolean equals(Object oo)
      {
        HashValue hh=new HashValue();
        if(oo instanceof HashValue) 
           hh = (HashValue)oo;
    
        if(this.x==hh.x)
          return true;
        else
          return false;
      }
    
       HashValue()
      {
         x=11;
       }
    
      }
    
     class  Hashing
     {
         public static void main(String args[])
        {
           HashValue hv=new HashValue();
           HashValue hv2=new HashValue();
    
          System.out.println(hv.hashCode());
          System.out.println(hv2.hashCode());
    
          if(hv.equals(hv2))
            System.out.println("EQUAL");
          else
             System.out.println("NOT EQUAL");
        }
      }
    

提交回复
热议问题