Win a copy of Design for the Mind this week in the Design forum!

# Help me with equals! - I've exam tomorrow

Malgorzata Klos
Greenhorn
Posts: 3
I make mock exam, and I have question:

class A {
String a;
int c;
short b;

public int hashCode() { return a.length() * c;}

public boolean equals(Object o) {
//insert code
}
}
Insert code, that fulfill contract between equals and hashCode

And one from correct answer is:
((A)o).a.lenght() * ((A)o).b * ((A)o).c == this.code.lenght() * this.b * this.c;

I don't understand why...
If o1 has code="a", b=2, c=3 and
o2 has code="a", b=3, c=2 then
o1.equals(o2) == true, but o1.hashCode() != o2.hashCode !!!

Rajeev Rnair
Ranch Hand
Posts: 310
1
Hi Malgorzata, welcome to the ranch!

Could you tell me the source of this question? Also please use "Code" tags so that your code is more readable to others!
The rule is:
If hashCode() is same, equals() may be true, may not be true
If equals() is true, hasCode() needs to be same.

Good luck for the exam!

Thanks,

Malgorzata Klos
Greenhorn
Posts: 3
Hi,
I bought book by Kathy Sierra & Bert Bates with CD contains Master Exam. This question is from quiz A: question 52.

Ankit Garg
Sheriff
Posts: 9510
22
Malgorzata I believe you are right, the answer is wrong. I think this question has been bought up before too and there is definitely a mistake in the question...

Larry Olson
Ranch Hand
Posts: 142
I am reposting the above code for clarification.

I don't understand why...
If o1 has code="a", b=2, c=3 and
o2 has code="a", b=3, c=2 then
o1.equals(o2) == true, but o1.hashCode() != o2.hashCode !!!

I do agree with your statement. In this case even though objects being equal is "true", hashCodes be equal is "false". This seems to violate the equals hashCode contract. May be I am overlooking something?

Malgorzata Klos
Greenhorn
Posts: 3
I attach oryginal question with answer. Maybe I rewrite something wrong?
But all time I don't think why D is correct - I hope, that I have'nt this question on exam.
screen.JPG

kaushik vira
Ranch Hand
Posts: 102

Output:-
true
true
code=a,b=3,c=3
code=a,b=2,c=3

Above example may help to understand the answer. In your current example hash code method implementation is not strong. but equals method making sure that object equality.

Prithvi Sehgal
Ranch Hand
Posts: 774
Dear Kaushik,

I guess Malgo is write. He has given the following values and tested

If o1 has code="a", b=2, c=3 and
o2 has code="a", b=3, c=2 then

Though objects being equal, but their hashcode is returning false. So i think so there is a mistake in the question for sure.

Best Regards,