posted 20 years ago
This would be easier if we knew what the sample test quesion was asking for. If it's asking which statements produce legal hashcodes, all of them do. If it's asking which produces the best hashcode, then I agree with (E), though I could also talk myself into (D).
My rule of thumb is that a hashcode should do a pretty good job of reflecting the uniqueness of an instance, by being a function of the instance's important state variables. What's that mean? It's open to debate, but the contract (see API page for Object.hashCode()) is that if a.equals(b) then a.hashCode() == b.hashCode().
The reason for all this is so that collections will work properly. Many collections (especially map implementations) use hashcodes to figure out how to store their contents. If a hashcode algorithm doesn't do a good job of distinguishing unequal objects (remember, unequal obs may have the same hashcode: it's just the reverse case that's forbidden) then collections perform inefficiently. On the other hand, if a hashCode() method always returns unequal hashcodes for unequal objects, that' not always ideal either. If the algorithm performs a ton of computation on the instance's state variables, then any collection that calls hashCode() will still run inefficiently.
So the point is to have a hashCode() method that strikes a good balance between distinction and performance.
What about the rule that only final variables should be part of the calculation? Well, if you stick to that you'll never get into a certain kind of trouble that's really hard to debug. If an object is stored in a collection, and that object's state changes in a way that affects hashCode() and/or equals(), really weird things can happen. So if the state is final, you can never experience those really weird things. However, I don't always make my state final, because sometimes I just can't. But when I have non-final state, I'm extra careful.
Hope this helps.
Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".