• 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

regarding hashCode() method

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Choose any three that apply
Given the following class, which are correct implementations of the hashCode() method?

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.
}
}

Answers

1. return 0;
2. return a;
3. return a+b;
4. return a-b;
5. return a^b;
6. return (a<<16)|b;

I'm sure that hashCode() method can
5. return a^b (an exclusive OR operation) and
1. return 0;

What is the other one which it can return.. with justification...
Thanks in advance... !!
rAm
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The other one should be a+b

object with a,b values 1,2 and 2,1 would be equal and their hashcodes would return 3. Works for negative numbers too.

not so for a-b.

object 1,-2 and -2,1 one would return +3 and the other -3 for a-b
 
Ramkumar Kannan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why cant it return a or (a<<16)|b ??

Can u explain ??

Thanks in advance..
~rAm
 
Do Re Mi Fa So La Tiny Ad
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic