Accenture Interview Question
Country: India
Interview Type: Phone Interview
There wont be any compile time or run time exceptions but i would never like my hashcode returning 0 . It is usually some distinct values which you would like to derive from some class level variables which are also defining the functioning of your equals method. (Note : this is an example) . Two equal objects should produce the same hash code .
I'd recommend you to read the concept of hashing.
Nevertheless, let me try to answer.
Hashing is generally used for fast retrieval, preferably in constant time.
If your hashCode always returns the same integer then all of your items will be inserted in one bucket. And when you try to access an item, it will locate the only bucket based on hashCode and then do a linear search in that only bucket to find the item. The time complexity will be O(n). Had you written a good hashCode method, the time complexity would have been constant.
You are explaining hash function and not the hashCode function. The reason for hashCode function is that it helps in implementing the equals method. So, you compare 2 objects member by member iff the hashcode for the is same.
So, if we implement a good hashCode function then we will reduce the chances of doing full comparison in the cases where the objects aren't actually equal. If the hashCode keeps returning 0 then we will be doing full comparisons in all the cases and hence having implemented hashCode doesn't really solve any purpose.
It will compile. Its not a good practice to return any constant number from hash code.
- santhosh May 01, 2012Please search for hashcode and equals method contract for better understanding