File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashCode() method contract Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashCode() method contract" Watch "hashCode() method contract" New topic

hashCode() method contract

Percy Dadabhoy

Joined: Mar 26, 2007
Posts: 26
K&B's book mentions that the hashCode() method implementation can be described in three ways-

1. By LEGAL I understand that the method must meet the method contract.

2. By APPROPRIATE I understand that the generated hashCode() should be unique or as random as possible so as to obtain a good distribution of values.

3. I do not then understand what is meant by a CORRECT implementation. Don't the above two adjectives describe it sufficiently? Or, is CORRECT a 'mild' form of APPROPRIATE - for e.g. an implementation that returns a constant for all values would be CORRECT, but since it is absolutely inefficient, it can't be termed as APPROPRIATE.

Please clarify.

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

1. I think that we both understand the same that LEGAL means not only is hashCode() overriden and the code compiles, but that if you call hashCode() on the same object, the same value is returned unless the object has been mutated in such a way that it is not equals() to what it was before it was mutated.

2. I believe that K & B is using APPROPRIATE & CORRECT as synonyms. I think that you and I have the same understanding, yet I would not use the word "random". I think that more accurate terminology would be "uniform distribution" of the values of the hashCode() method since being "random" breaks the hashCode() method's contract.

Matt Russell
Ranch Hand

Joined: Aug 15, 2006
Posts: 165
K&B use (at least) four terms in relation to hashCode overrides: legal, appropriate, correct and efficient. In the summary notes at the end of chapter 7, they say that "an appropriate hashCode() override sticks to the hashCode() contract" and "an efficient hashCode() override distributes keys evenly across its buckets". Unfortunately they don't set out definitively what they mean by "correct" and "legal" (unless I missed it).

Inquisition: open-source mock exam simulator for SCJP and SCWCD
Percy Dadabhoy

Joined: Mar 26, 2007
Posts: 26
Yes Matt, they also use the term efficient to describe the hashCode() method - I missed mentioning that.

And Kaydell, I accept your point that 'uniform distribution' is more appropriate than 'random'.

Thanks for replying - I guess more people need to give their thoughts before we can come to any conclusion.

I agree. Here's the link:
subject: hashCode() method contract
It's not a secret anymore!