This week's giveaway is in the Groovy forum.
We're giving away four copies of Groovy Fundamentals video training course and have Ken Kousen on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Groovy Fundamentals video training course this week in the Groovy forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections" Watch "Collections" New topic


Nikhil Jain
Ranch Hand

Joined: May 15, 2005
Posts: 385
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

SCJP 1.4, SCWCD 1.4, SCBCD 1.5
Rob Spoor

Joined: Oct 27, 2005
Posts: 19991

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.

How To Ask Questions How To Answer Questions
Consider Paul's rocket mass heater.
subject: Collections