Why can not I use toString().length() as a hashCode() return?

2.1k views Asked by At
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?

1

There are 1 answers

2
Rohit Jain On BEST ANSWER

If you see the source code of toString method of Object class, it looks like: -

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So, it internally invokes hashCode() method. Now, since you have overrided the hashCode method, it will invoke the hashCode method of your class, which agains invokes toString method of Object 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 in equals method, to maintain the contract between hashCode and equals method. Use only those attributes in calculating hashCode that you have used to compare your instances in equals method.

See these links for more details on hashCode and equals method:-