Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode question

 
Don Bosco
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, but you'll get better hashing performance
if you do. The fewer hash collisions (unequal objects with equal hash codes), the better.
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No
 
Don Bosco
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx guys!
 
Deepa
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it necessary for the hashCode method to use these variables at all?
Thanks.
Deepa
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic