wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections" Watch "Collections" New topic
Author

Collections

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
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
 
subject: Collections
 
Similar Threads
Understanding hashcode()
Thread topic Help needed
Question 80 from Java rules round up
abstract class
Inner class question from Dan's exam