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 ]
I tend to agree with Daniel. I think the problem in the original statement is the author might not have taken into account that some integers can be written as a product in different ways.
Bert Bates
author
Sheriff
Joined: Oct 14, 2002
Posts: 8439
posted
0
Dang
Okay, let's turn this into a "learning opportunity"
I'm not thrilled with this, but how about if d). was something like this:
Eliminate fossil fuel subsidies. (If you're not on the edge, you're taking up too much room.)
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2306
posted
0
I guess the issue bowls down to the following propositions.
Proposition 1: If a,b,c, and a1,b1,c1 are integers and a*b*c = a1*b1*c1, then a*b=a1*b1.
This proposition is shown to be false with the sets of numbers 2,3,2 and 4,1,3.
Proposition 2: If a,b,c and a1,b1,c1 are integers and a*b+c = a1*b1+c1, then a*b=a1*b1.
This proposition can also be shown to be false with the sets of numbers 2,4,1, and 2,3,3.
[ March 15, 2006: Message edited by: Keith Lynn ] [ March 15, 2006: Message edited by: Keith Lynn ]
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18652
posted
0
[BB]: Got any better ideas?
1: Just make the answer C only.
2: Replace D with a more traditional equals method like
or
or even
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
Bert Bates
author
Sheriff
Joined: Oct 14, 2002
Posts: 8439
posted
0
so far i like jim's option 3 the most...
Daniel Svensson
Greenhorn
Joined: Mar 15, 2006
Posts: 2
posted
0
Thanks for your input. It's good to know that I wasn't on the wrong track after all.
Daniel
subject: equls/hashCode in MasterExam possible error