aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes mistake in k&b hashCode()/equals() contract question 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 "mistake in k&b hashCode()/equals() contract question" Watch "mistake in k&b hashCode()/equals() contract question" New topic
Author

mistake in k&b hashCode()/equals() contract question

Paul Lachance
Greenhorn

Joined: Nov 27, 2006
Posts: 10
There is a question on the K&B CD that I suspect has an incorrect solution...

The question is:

Given:
class SortOf {
String name;
int bal;
String code;
short rate;
public int hashCode() {
return (code.length() * bal);
}
public boolean equals(Object o){
// insert code here
}


Which of the following will fill the equals() and hashCode() contracts for this class?

A. return((SortOf)o).bal == this.bal;
B. return((SortOf)o).code.length() == this.code.length();
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 selected C (which is correct) but the solution mentions that D is also correct. As far as I can tell D should NOT be correct since there are values of code.length(), bal and rate such that equal SortOf's could have different hashCodes!

for example, if one SortOf has code="blah" (length=4), bal=2 and rate=3, and another SortOf has code="da" (length=2), bal=3 and rate= 4, then the SortOf's are equal() but they have different hashCodes which violates the contract.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Just search this forum for "SortOf" and you come up with: this topic, amongst several others.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: mistake in k&b hashCode()/equals() contract question