Hi all, In the MasterExam shipped with the K&B 5.0 book there is a question concerning the equals() and hashCode() contract:
Answer is C & D.
I'm fine with C but D?? Think about it. Say that you have two SortOf objects a & b, initialized as follows:
a.equals(b) would then return true (as 3*2*2 == 4*1*3). According to the contract a.hashCode() and b.hashCode() must therefore return the same value. But they don't: a.hashCode() is 4*1=4 and b.hashCode() is 3*2=6!!
It would be nice if someone could verify this and tell me if I'm right or if I've overlooked something. Thanks. [ March 15, 2006: Message edited by: Daniel Svensson ]
2: Replace D with a more traditional equals method like
3: Replace D with the nontraditional but valid
I'd also note that in fact, none of these methods are truly valid except "return this == other;". The reason is that they all can throw ClassCastException or NullPointerException if reference o is the wrong class, or null. The correct response would be to simply return false. This could be fixed with an instanceof check, e.g.:
[ March 15, 2006: Message edited by: Jim Yingst ]
"I'm not back." - Bill Harding, Twister
Joined: Oct 14, 2002
so far i like jim's option 3 the most...
Joined: Mar 15, 2006
Thanks for your input. It's good to know that I wasn't on the wrong track after all.