I have below code which overrides equals() and hashcode() methods.
public boolean equals(Object obj)
{
if (obj == null)
return false;
if (!(obj instanceof Name))
return false;
Name name = (Name) obj;
return this.name.equals(name.name);
}
public int hashCode()
{
return name.hashCode();
}
here can i replace below 2 lines:
return this.name.equals(name.name);
return name.hashCode();
with
return this.getName().equals(name.getName());
return getName().hashCode();
i mean instead of using properties can i directly use getters inside equals and hashcode methods?
Thanks!
If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.
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. It is not required that if two objects are unequal according to the equals(java.
The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.
The Contract Between equals() and hashcode()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.
Yes sure you could use this,
hashcode()
and equals()
are field methods, They can access private members directly, but what if there is some logic wrapped in accessor method, so it is always safe to access fields using accessor methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With