This week's book giveaway is in the Cloud/Virtualization forum.We're giving away four copies of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds and have James Denton on-line!See this thread for details.
Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
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:
• Liutauras Vilda
• Campbell Ritchie
• Tim Cooke
• Bear Bibeault
• Devaka Cooray
Sheriffs:
• Jeanne Boyarsky
• Knute Snortum
• Junilu Lacar
Saloon Keepers:
• Tim Moores
• Ganesh Patekar
• Stephan van Hulst
• Pete Letkeman
• Carey Brown
Bartenders:
• Tim Holloway
• Ron McLeod
• Vijitha Kumara

Collections

Ranch Hand
Posts: 392
public class Quiddler {
private int x, y;
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj != null && obj.getClass() == this.getClass()) {
return ((Quiddler)obj).x == x;
} else {
return false;
}
}
public int hashCode() {
// insert statement here
}

Option 1: return y = 0;
Option 2: return x + y;
Option 3: return y;
Option 4: return x * 13;
Option 5: return x;

The answerws are 1,4,5. Can you guys explain this. I mean, what is the catch in this kind of questions

Sheriff
Posts: 21453
96
It's about correct implementations of equals and hashCode.

equals only looks at x and not at y, so hashCode should not look at y. Options 4 and 5 only look at x so these match.
Option 1 however does not return just y - it sets y to 0 and only then returns y (or 0).

Remember, returning a constant is always a correct (yet inefficient) implementation for hashCode.

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