i have the snippet of code od SCJP book
Which code, when inserted at (1), will provide a correct implementation of the
hashCode() method in the following program?
Select the two correct answers.
(a) return 31337;
(b) return accumulated / count;
(c) return (count << 16) ^ accumulated;
(d) return ~accumulated;
(e) return count == 0 ? 0 : average();
the correct answer is (a) and (e)
(b) is incorrect because of count if it is null it will genearte arithmetic Exception
but i don't now the mean of (c) and (d) and why are false
For both (c) and (d), the problem is that they are not consistent with the implementation of equals(). You need to study how the equals() method is implemented, and compare that with the possible implementations of hashCode(). We can see that the equals() method uses count and average() - it doesn't use accumulated at all. So right away, it should cause some concern if we see a hashCode() implementation that uses accumulated - such as b, c, or d. The question is, is there any way that you can have two instances that are equal, as far as equals() is concerned, but have different hashcodes? Because that is not allowed.
(The converse, instances that are not equal but have the same hashcode, is allowed - it's just inefficient. So we ignore that case here.)
Consider two instances a and b:
What will happen if we run this, with code from (b), (c), or (d)? (Or (a) or (e)?) Will the results make sense? Try compiling and running the code yourself to see.
a fool thinks himself to be wise, but a wise man knows himself to be a fool - shakespeare. foolish tiny ad:
Create Edit Print & Convert PDF Using Free API with Java