Win a copy of Rust Web Development this week in the Other Languages forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

how to analyis which is correct hashcode?

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

class ValuePair {
public int a, b;
public boolean equals(Object other) {
try {
ValuePair o = (ValuePair) other;
return (a == o.a && b == o.b)
|| (a == o.b && b == o.a);
} catch (ClassCastException cce) {
return false;
}
}
public int hashCode() {
// Provide implementation here.
}
}

and to insert correct implementation among these... u need to choose three.
1)return 0;
2)return a;
3)return a+b;
4)return a-b;
5)return a^b;
return (a 16)|b;


please help me on this...also please explain your answers thank you

Cecilia
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The correct answers are 1), 3), 5)

There are 2 requirements in the contract + one indication (it is appropriate to respect it)
a. to return the same hash code between calls if the object's state is not changed.
b. if x.equals(y) is true than it is required that x.hashCode() == y.hashCode()
c. if x.equals(y) is false than it is appropriate but not required that x.hashCode() != y.hashCode()


Back to the question:
a. is true for all 5 answers
b. is true only for 1), 3), 5),
1) because in any case x.hashCode()== y.hasCode()
3), 5) use commutative operations (a+b==b+a) ,( a^b = b^a) and so the b) is satisfied given this particular equals implementation
for example: ob1 = (1,2) , ob2= (2,1)
c) is not required

For '6)' return (a 16)|b; - the code will not compile
[ August 29, 2005: Message edited by: Balazs Borbely ]
 
Cecilia Jane
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much!!!



Cecilia Jane
 
Nothing up my sleeve ... and ... presto! A tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic