Alex Rivera | Logout

hashCode() purpose in Java

Asked 2013-02-06T17:32:07.047
8

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?

Edit
Report

1 Answer

1

A hash code is a just a "value". It has nothing more to do with "where you put it in memory" than "MyClass obj = new MyClass()" has to do with where "obj" is placed in memory.

So what is a Java hashCode() all about?

Here is a good discussion on the subject:

K&B says that the hashcode() contract are :

  1. If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.

  2. If two objects are unequal according to the equals(Object) method, there's no requirement about hashcode().

  3. If calling hashcode() on two objects produce different integer result, then both of them must be unequal according to the equals(Object).

answered 2013-02-06T17:35:05.233

Your Answer