Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode() method contract

 
Percy Dadabhoy
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
K&B's book mentions that the hashCode() method implementation can be described in three ways-
1. LEGAL
2. APPROPRIATE
3. CORRECT

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.

Regards
Percy
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Kaydell
 
Matt Russell
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Percy Dadabhoy
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Regards
Percy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic