programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Devaka Cooray
• Liutauras Vilda
• Jeanne Boyarsky
• Bear Bibeault
Sheriffs:
• Paul Clapham
• Knute Snortum
• Rob Spoor
Saloon Keepers:
• Tim Moores
• Ron McLeod
• Piet Souris
• Stephan van Hulst
• Carey Brown
Bartenders:
• Tim Holloway
• Frits Walraven
• Ganesh Patekar

# help wme with this question

Ranch Hand
Posts: 38
Given the following class, which are correct implementations of the hashCode() method?

class ValuePair {
public int a, b;
public boolean equals(Object other) {
try {
ValuePair o = (ValuePair) other;
return (a == o.a && b == o.b)
|| (a == o.b && b == o.a);
} catch (ClassCastException cce) {
return false;
}
}
public int hashCode() {
// Provide implementation here.
}
}

a) return 0;
b) return a;
c) retrun a+b;
d) return a-b;
e) return a^b;
f) return (a<<16);

These were the options given the answer is given as a,c,e and i dont know how they are givin this as answer. when i compiled with these options all the options copiles please tell me me how this answer is got.

Ranch Hand
Posts: 83

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html under hashCode()

- Must return the same integer result which results in the same comparison equals() provides.

In this example, equals is provided. If the integers match self, or their pair, it returns equals.

b) return a; -- This fails because if you had (4,5) (5,4) it should return equal values, this will not. (it would return 4 5 which are not equal)

d) return a-b; -- Again this fails with (4,5) (5,4). One returns 1, the other -1. These are not equal.

f) return (a<<16); This is similar to b. But do all integers left shifted 16 times return the same value? No. If this were a<<32 I think it would be a valid answer.

a) return 0;
c) retrun a+b;
e) return a^b;

All of these return the same equals values. All the expressions are commutative. You could also use (a*b), 27, b + a + b + a, 3*b + 3 * a

You could not use a/b or b/a or b or b*b or a*7.

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.