class equals and hashcode in Java

We have seen in out Sets example that if we add two user defined class objects of class Planet to the set ,both will be added as Java .equals method considers two different objects to be different as its implementation compares object memory addresses, so it works the same as the == operator for String.

So if we want .equals method to compare equal for our user defined class if some variable name is the class are same then we have to override that method in our class

    @Override
    public boolean equals(Object obj) {
     //The below line of code if object is compared to itself it returns true as 
    //== returns true if objects compared are same objects in memory
     if (this == obj) return true;
        System.out.println("obj.getClass() is "+obj.getClass());
        System.out.println("this.getClass() is "+this.getClass());
    //        If class is not equal i.e if class for obj or this class ins not same i.e mycollections.HeavenlyBody. Here we make sure that subclasses don’t 
    compare equal so that’s why we check if obj passed if of same class as the class in which this method is i.e HeavenlyBody.
      if(obj==null||obj.getClass()!=this.getClass())
            return false;
      String objName = ((HeavenlyBody)obj).getName();
     System.out.println(this.name + "============"+((HeavenlyBody)obj).getName());
     return this.name.equals(objName);
    }

For .equals to work we have to overide the hashcode method as well in that class. Hashcode will be called when we need to compare two Heavenly Body objects , but if of the objects have same hash code i.e if they are in the same bucket then equals will be called and it will compare the objects using equals method as well

    @Override
    public int hashCode() {
       //Every instance of an object has hash code  0 so it misses the purpose somehow.
        // So all objects will have same hash code and will end in same bucked.So we will
        //have to add a random number to the hashcode so that its not 0.
        System.out.println("hashCode is "+this.name.hashCode()+57);
    //Here we are just returning the hash code for the field name of the heavenly body //class as in equals method also we are comparing objects based 
     //on this field name itself.
   return this.name.hashCode()+57;
    }
}