• 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

help wme with this question

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
}
}

a) return 0;
b) return a;
c) retrun a+b;
d) return a-b;
e) return a^b;
f) return (a<<16);

These were the options given the answer is given as a,c,e and i dont know how they are givin this as answer. when i compiled with these options all the options copiles please tell me me how this answer is got.
 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The hashcode must complete the following things (as per this page)

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html under hashCode()

- Must return the same integer result which results in the same comparison equals() provides.

In this example, equals is provided. If the integers match self, or their pair, it returns equals.

b) return a; -- This fails because if you had (4,5) (5,4) it should return equal values, this will not. (it would return 4 5 which are not equal)

d) return a-b; -- Again this fails with (4,5) (5,4). One returns 1, the other -1. These are not equal.

f) return (a<<16); This is similar to b. But do all integers left shifted 16 times return the same value? No. If this were a<<32 I think it would be a valid answer.

a) return 0;
c) retrun a+b;
e) return a^b;

All of these return the same equals values. All the expressions are commutative. You could also use (a*b), 27, b + a + b + a, 3*b + 3 * a

You could not use a/b or b/a or b or b*b or a*7.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic