File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes legal equal() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "legal equal()" Watch "legal equal()" New topic

legal equal()

adolfo bulfoni

Joined: Aug 13, 2008
Posts: 2
took from Master Exam A (SCJP6 book)

which of the following will fulfill the equals() and hashCode() contracts for this class?

Correct answers:

C: return ((SortOf)o).code.length()* ((SortOf)o).bal == this.code.length()*this.bal();

D: return ((SortOf)o).code.length()* ((SortOf)o).bal * ((SortOf)o).rate == this.code.length()*this.bal() * this.rate;

I think only "C" is correct answer..
example (with D answer):

this.code.length() = 2;
this.bal() = 1;
this.rate = 5;

((SortOf)o).code.length() = 5;
((SortOf)o).bal() = 1;
((SortOf)o).rate = 2;

o hashCode is 2
this hashCode is 5 (different hashcodes => different objects)


this.equals(o) is TRUE! (10 == 10) => D is false

What do you think?
vidhya suvarna
Ranch Hand

Joined: Aug 28, 2008
Posts: 148
Yes, option c seems to be correct accordingly to me too.

SCJP 1.4 - 88%<br />SCWCD 1.5 - Preparing
Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

Yes only C is the correct answer. There was a long discussion on this question some time ago and the outcome was that only C is correct...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

Yes. Option C is correct

Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Aravind Jerubandi
Ranch Hand

Joined: Dec 17, 2006
Posts: 49
Hi Ranchers,

I'm not very good at Java. But somehow i feel that, there is nothing wrong with the equals comparison in option D. it doesn't break any contact of equals comparison. So, both options C and D are correct.

i think the hashcode implementation is not correct in this particular case. As per the hashCode contract:

"If two Objects are equal as according to equals method then calling the hashCode() method on each of the two objects must produce the same integer result"

this doesn't say other way round. So, i think the equals comparison is correct in both the options. And the hashCode implementation is not correct.


-Aravind<br />SCJP 5.0 (91%), Preparing for SCBCD.
I agree. Here's the link:
subject: legal equal()
It's not a secret anymore!