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 question 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 question" Watch "hashCode question" New topic

hashCode question

Don Bosco
Ranch Hand

Joined: Oct 31, 2002
Posts: 108
class A{
int i;
int j;
assume that the above class overrides equals method and uses both variables i and j for comparing two objects of this class.
Is it necessary for the hashcode method to use both of these variables in calculating the hash???

SCJP 1.4<p>Wingardium Leviosa!!
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
No, but you'll get better hashing performance
if you do. The fewer hash collisions (unequal objects with equal hash codes), the better.

Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Michael Ernest
High Plains Drifter

Joined: Oct 25, 2000
Posts: 7292

Don Bosco
Ranch Hand

Joined: Oct 31, 2002
Posts: 108
thanx guys!

Joined: Aug 22, 2002
Posts: 10
Is it necessary for the hashCode method to use these variables at all?
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Joshua Bloch wrote in Effective Java that for the hashCode method all the fields taken into account by equals should be used.
However I undertand that it would be admisible to use only one, say "i":
a) Two objects considered equal (same i, and same j) would end up into the same bucket (in a hash structure), because their fields "i" are the same and hashCode produces the same value.
b) Two objects with the same "i" but different "j" still go to the same bucket. But potentially many more objects could end up in the same bucket than if we were using a hashCode that considers both "i" and "j"; all of them with the same "i" but a different "j". The result is that the sequential search in the bucket for objects to be comnpared with equals would degrade the goal of a hash structure --performance.
Joshua also wrote:

Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance (in the computation)...
...quality might degrade to the point where hash tables become unusably slow.

SCJP2. Please Indent your code using UBB Code
I agree. Here's the link:
subject: hashCode question
It's not a secret anymore!