The author of the question says the answer is D, but I wonder why the answer should not be C??
Q: Which statement is true about the code that can fill in the blank?
class Sticker {
public int hashCode() {
return 1;
}
public boolean equals(Object o) {
return____________ ;
}
}
A. It must return false.
B. It must return true.
C. It can return either true or false.
D. None of the above.
EDIT 1 :
The answer and explanation for it given by the author is following: If two instances of a class have the same hash code, they might or might not be equal. The reverse is not true. If two objects are equal, they must have the same hashcode in order to comply with the contracts of these methods. However, in this case, the answer is none of the above because the method can't simply return true or false. Based on the rules of equals(), if null is passed in, the result must be false. If an object identity is passed in, the result must be true due to reflexivity. As a result, Option D is correct.
EDIT 2 : May be the author means the following by his explanation given above: I think may be the author wants to say that if we return true
from the equals(Object)
then there is a possibility that somebody could pass a null
in the equals(Object)
in which case it will be contradicting the return value true
as based on null
argument being passed the return value should be false
not true
. Similarly, if we return false
then there is a possibility that a Sticker
object identity is passed and then it'll again be contradicting. So basically we can't really fill in the blank with either true
or false
. May be that was why author said the answer was D.
The author has poorly written the answer options. It is clear from their explanation that their answer choices would be better written as:
A. It should always return false. B. It should always return true. C. Returning true or returning false are always both correct. D. None of the above.
The question might also benefit from a rewrite:
Assuming the code which fills in the blank correctly fulfills the contract of the equals() method, which statement below is always true?
The author has committed two grievous infractions against computer science
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.