public class Dog
{
int collarID;
String name;
public static void main(String[] args){
Dog d = new Dog();
d.name="hose";
System.out.print(d.hashCode());
}
public boolean equals(Object arg0)
{
if (arg0 instanceof Dog)
{
Dog new_name = (Dog) arg0;
return collarID==new_name.collarID && new_name.name.equals(name);
}
return false;
}
public int hashCode()
{
return toString().length();//StackOverflow
}
}
What am I missing? Is there a recurrent call to hashCode() method because of default toString() method?
If you see the source code of
toString
method ofObject
class, it looks like: -So, it internally invokes
hashCode()
method. Now, since you have overrided thehashCode
method, it will invoke thehashCode
method of your class, which agains invokestoString
method ofObject
class.This will certainly result in
StackOverFlowError
You can rather override the
toString
method in your class, to make it work.P.S.: -
However, your
hashCode
implementation should be designed, considering the attributes you have used inequals
method, to maintain thecontract
betweenhashCode
andequals
method. Use only thoseattributes
in calculatinghashCode
that you have used to compare yourinstances
inequals
method.See these links for more details on
hashCode
andequals
method:-Effective Java - Item # 8 - Obey the general contract when overriding equals
Effective Java - Item # 9 - Always override hashCode when you override equals