Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Collections

 
Ranch Hand
Posts: 393
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 22791
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Something about .... going for a swim. With this tiny ad ...
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic