This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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
posted
0
No, but you'll get better hashing performance if you do. The fewer hash collisions (unequal objects with equal hash codes), the better.
Is it necessary for the hashCode method to use these variables at all? Thanks. Deepa
Jose Botella
Ranch Hand
Joined: Jul 03, 2001
Posts: 2120
posted
0
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: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.