Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# legal equal()

Greenhorn
Posts: 2
took from Master Exam A (SCJP6 book)

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

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..

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
Posts: 148
Yes, option c seems to be correct accordingly to me too.

Ankit Garg
Sheriff
Posts: 9542
33
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...

chander shivdasani
Ranch Hand
Posts: 206
Yes. Option C is correct

Aravind Jerubandi
Ranch Hand
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.

 It is sorta covered in the JavaRanch Style Guide.