// The worst possible legal hash function - never use! @Override public int hashCode() { return 42; }
Its validity, as it guarantees that equal objects have the same hash code. Its atrocious because it guarantees that every object has the same hash code. Therefore, each hash of objects in the same bucket, and hash tables degenerate into linked lists. Programs that must be run in linear mode are executed in quadratic time.
I am trying to understand the above (quote from page 47, paragraph 9, Joshua Bloch Effective Java).
As I see it, it looks like this (consider the following code):
Map<String, String> h = new HashMap<String,String>(); h.put("key1", "value1"); h.put("key1", "value2");
What happens to the second h.put("key1",...) command h.put("key1",...) : 1. Get the hash code of key1 2. Go to the bucket representing the above hash code 3. Inside this bucket for each object, call the equals method to find whether an identical object exists.
It is rather faster, because first you discover a "group" (bucket) of objects, and then the actual object.
Now that the hashcode implementation is such that it returns the same integer (for example, 42 above) for ALL objects, then there is only one bucket, and the equals method should be called one after the other on each object as a whole hashmap / hashtable. This is as bad as a linked list, because if the objects that are in the linked list, you also need to go through them one by one, comparing (calling equal) each object.
That's why it has been said that hash tables degenerate into a linked list?
(I apologize for the verbosity of the above text. I am not clear enough in my concepts to say this more briefly)