Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hashCode() purpose in Java

Tags:

java

hashcode

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?

like image 439
gabriel angelos Avatar asked Feb 06 '13 17:02

gabriel angelos


People also ask

Why do we need hashCode?

HashMap and HashSet use the hashcode value of an object to find out how the object would be stored in the collection, and subsequently hashcode is used to help locate the object in the collection.

What is the hashCode () and equals () used for?

Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.

Why hashCode is used in HashMap?

In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.

What type of value does hashCode () return?

Simply put, hashCode() returns an integer value, generated by a hashing algorithm. Objects that are equal (according to their equals()) must return the same hash code.


1 Answers

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.

like image 190
Jon Skeet Avatar answered Oct 07 '22 05:10

Jon Skeet