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
toStringmethod ofObjectclass, it looks like: -So, it internally invokes
hashCode()method. Now, since you have overrided thehashCodemethod, it will invoke thehashCodemethod of your class, which agains invokestoStringmethod ofObjectclass.This will certainly result in
StackOverFlowErrorYou can rather override the
toStringmethod in your class, to make it work.P.S.: -
However, your
hashCodeimplementation should be designed, considering the attributes you have used inequalsmethod, to maintain thecontractbetweenhashCodeandequalsmethod. Use only thoseattributesin calculatinghashCodethat you have used to compare yourinstancesinequalsmethod.See these links for more details on
hashCodeandequalsmethod:-Effective Java - Item # 8 - Obey the general contract when overriding equalsEffective Java - Item # 9 - Always override hashCode when you override equals