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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Ron McLeod
• Tim Cooke
• Junilu Lacar
Sheriffs:
• Rob Spoor
• Devaka Cooray
• Jeanne Boyarsky
Saloon Keepers:
• Jesse Silverman
• Stephan van Hulst
• Tim Moores
• Carey Brown
• Tim Holloway
Bartenders:
• Jj Roberts
• Al Hobbs
• Piet Souris

# equals and hashcode

Ranch Hand
Posts: 142
• Number of slices to send:
Optional 'thank-you' note:
Hi
This is a question from PGJC exam.
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.
}
}
1.return 0
2. return a
3. return a+b
4.return a-b;
5. return a^b
6. return (a16)|b
I selected the options 3,4,5 but not sure.
-Sanjana

Greenhorn
Posts: 3
• Number of slices to send:
Optional 'thank-you' note:
I believe 1, 3, 5 are the options. Not quite sure about 6. If it is a | b then it should be the answer.

sanjana narayanan
Ranch Hand
Posts: 142
• Number of slices to send:
Optional 'thank-you' note:
Hi Sam Chen,
why is that a-b cannot be one of the option. Any reasons?
-Sanjana

Wanderer
Posts: 18671
• Number of slices to send:
Optional 'thank-you' note:
Sam is correct that 1, 3, and 5 are the answers. 6 is nonsense as written - surely PGJC wrote something else here?
why is that a-b cannot be one of the option. Any reasons?
Yes. Consider two objects:
Given the definition of equals(), these two objects are equal. Therefore, their hashCode() methods must return the same values. But they don't. Answers 2 and 4 are incorrect because they would both return unequal hash codes for equal objects.

 You showed up just in time for the waffles! And this tiny ad: Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton