Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

legal equal()

 
adolfo bulfoni
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, option c seems to be correct accordingly to me too.
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. Option C is correct
 
Aravind Jerubandi
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic