What would be the ans of the following q? Given the following class, which are correct implementations of the hashCode() method?
Select 3 correct answers: (A)return 0; (B)return a; (C)return a+b; (D)return a-b; (E)return a^b; (F)return a|b; I don't know the answers..because Khalid's mock does not give the right answers. Can someone explain it to me. Monisha.
Well, Monisha, let me answer a question with a question. Which answers do you think are correct, and why? Don't worry - I'm not just going to leave you hanging entirely...here's a little help. From the API Spec for Object (Hashcode Method), this is what it says that Hashcode method must do:
The general contract of hashCode is: - Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. - If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. - It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
I was even feeling especially helpful and highlighted the most important element for this question. Now, what do you think the answer is? Corey
Hi Corey, Thanks for reminding me of a basic fact, I seemed to have easily overlooked. [Slap on the hand for myself] Ok I'll tell you how far I got So basically my object has 2 ints, a and b, and if the other object has the same 2 ints, they are equal. Order does not matter. Ok so now my hashCode() needs to return the same int for both these objects. Say Object1 has a=2 and b=5. And Object2 has a=5 and b=2. (A)return 0; - will work, but bad choice. (B)return a; - will not work, coz it will return 2 for Object1 and 5 for Object2 (C)return a+b; - will work. always returns the same result to both Objects. (D)return a-b; - will not work because it would return -3 for Object1 and 2 for Object2. (E)return a^b; - will work coz order won't matter. (F)return a|b; - will work coz order won't matter. So if I had to pick 3 I'd pick (C), (E) and (F) right?