Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.233 :

Posted: Tue Apr 15, 2014 2:30 am
by cosmindumy
"Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer.."

It is not clear for me.
If my hashCode is public int hashCode() {return i;}
and I update my i value, the hashCode implementation does not respect contract?

Re: About Question com.enthuware.ets.scjp.v6.2.233 :

Posted: Tue Apr 15, 2014 4:32 am
by admin
If the i that you are returning is also used in comparing this object with another then, no, it does not satisfy the contract.
The whole purpose of hash code is to be able to retrieve an object from a collection efficiently. Now, imagine that you store an object in a collection such as a HashSet. If you try to look for that object in that HashSet later, how will you find it if you change its internal data element that is used in equals relationship?

On the other hand if a data element is not used in comparison, there is little reason to use that member in computing the hash code.

You may read more about this here: http://docs.oracle.com/javase/7/docs/ap ... l#hashCode()