Java hashCode() Function Explanation and Purpose

hashcodejava

I read in a book that hashCode() shows a memory area which helps (e.g. HashSets) to locate appropriate objects in memory. But how can that be true if we cannot manipulate memory in Java directly? There are no pointers, in addition to it objects are created and moved from one place to another and the developer doesn't know about it.

I read that realization like hashCode() {return 42;} is awful and terrible, but what's the difference if we can't instruct VM where to put our objects?

The question is: what is the purpose of hashCode() on deep level if we can't manipulate memory?

Best Answer

I read in a book that hashCode() shows a memory area which helps (e.g. HashSets) to locate appropriate objects in memory.

No, that's a completely bogus description of the purpose of hashCode. It's used to find potentially equal objects in an efficient manner. It's got nothing to do with the location of the object in memory.

The idea is that if you've got something like a HashMap, you want to find a matching key quickly when you do a lookup. So you first check the requested key's hash code, and then you can really efficiently find all the keys in your map with that hash code. You can then check each of those (and only those) candidate keys for equality against the requested key.

See the Wikipedia article on hash tables for more information.

Related Question