aspose file tools*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "legal equal()" Watch "legal equal()" New topic
Author

legal equal()

adolfo bulfoni
Greenhorn

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)

BUT:

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
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

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.

PLEASE CORRECT ME IF I'M WRONG.


-Aravind<br />SCJP 5.0 (91%), Preparing for SCBCD.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: legal equal()
 
Similar Threads
Possible Wrong answer in k&b Master Exam
HashCode and Equals
Question on hashCode() & equals() from master exam 1
hashcode contract S&B question
K&B Master Exam Question 56