• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections

 
Nikhil Jain
Ranch Hand
Posts: 389
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Pie
Posts: 20613
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic