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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
cosmindumy
Posts: 7
Joined: Sun Apr 13, 2014 4:04 pm
Contact:

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

Post 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?

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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()

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 6 guests